LennyShort.com

Media Queries in CSS

Modern CSS has a feature called "media queries", which you can use to create different layouts, fonts, colors etc. for different size devices. For example, you could use a media query to create a mobile-friendly layout for your website that is dependent on the screen width of the device. Here's an example:

@media (min-width: 480px) {
    .section-two-image-container {
        flex-direction: row;
        justify-content: space-between;
    }

    .feature-image {
        width: 48.8%;     
    }
}

This media query acts as a sort-of "if-then" statement in CSS, where if the device's display width is 480 pixels or larger, the above CSS rules (flex-direction and justify-content) would take effect and override any other CSS rules that were in place on the same element. In this example, the elements with "section-two-image-container" and "feature-image" IDs would have the associated CSS rules applied to them.

The "and" keyword can be used to chain together multiple media query rules:

/* At the top level of your code */
@media screen and (min-width: 900px) {
  article {
    padding: 1rem 3rem;
  }
}

Logical operators can be used to compose a complex media query: "not", "and", and "only". Here's a more complex example that uses the "and" logical operator:

@media screen and (min-width: 30em) and (orientation: landscape) {
  /* … */
}

The not keyword inverts the meaning of a single media query. For example, the CSS styles in this media query will apply to everything except printed media:

@media not print {
  /* … */
}

To negate a single feature within a media query, use parenthesis. Encompassing a not and a media feature in parentheses limits the components of the query that get negated. In this example, we negate the hover media feature but not the all media type:

@media all and (not(hover)) {
  /* … */
}

You can use or to test for a match among more than one feature, resolving to true if any of the features are true. For example, the following query tests for devices that have a monochrome display or hover capability:

@media (not (color)) or (hover) {
  /* … */
}

Note that you cannot use the or operator on the same level as the and and not operators. You can either separate the media features with a comma or use parenthesis to group sub-expressions of media features to clarify the order of evaluation. For example, the following queries are both valid:

@media ((color) and (hover)) or (monochrome) {
  /* … */
}

/* or */
@media (color) and (hover), (monochrome) {
  /* … */
}

What I'm reading:

What I've read recently:

What's on my reading list: