Media Queries Overview

An overview of what I've learnt on media queries.

When creating a website the website must look good on different screen sizes. This ensures that the user has a good experience irrespective of what device they are on. This can be achieved by using media queries in our CSS.

Media outputs

Media queries can be used by using the @media keyword which can be used to target different outputs, not just device screens. For example, the @media print can be used to target print media i.e. when the website is being printed out.

@media print {
    body {
        color: black;
        background-color: white;
    }
}

Media default type

The default media type if you haven't specified any type is all. These two codes are the same.

body {
    color: black;
    background-color: white;
}

@media all {
    body {
        color: black;
        background-color: white;
    }
}

Media query conditions

Conditions can be added to the media type. These are called media queries. The CSS within the block is applied only if the condition is true. The conditions within the queries are called media features.

@media (min-width: 720px) {
 body {
 margin-inline: 5rem;
 }
}

@media (max-width: 720px) {
 body {
 margin-inline: 2rem;
 }
}

min-width: 720px can be read as the viewport must be at least 720px for the condition to be true. Conversely max-width: 720px can be read as the viewport must be at most 720px for the condition to be true.

Orientation

You can also change the style of the website based on the orientation of the screen i.e. whether it is in portrait or landscape orientation.

@media (orientation: landscape) {
  p {
    column-count: 2;
  }
}

@media (orientation: portrait) {
  p {
    column-count: 1;
  }
}

The above code changes the number of columns in a paragraph to two when the device is in landscape orientation and the number of columns to one when the device is in portrait orientation.