Tip of the week #004: Replace media queries with container queries

Container queries are here, and it’s possible to use them instead of width-based media queries

Container queries are useful if you need to change the look and behavior of components or layouts based on the context (containers) they’re being used in.

They don’t fully replace media queries, but it is possible to swap our width-based media queries for container queries.

You simply have to declare the html element as a container:

Language: css
html {
  container-name: viewport;
  container-type: inline-size;
}

@container viewport (min-width: 400px) {
  /* Do something */
}

And why you ask? Why not use @media screen (min-width: 400px) as usual?

Using container queries comes with some perks, like the benefits of using rem in our queries instead of pixels. Container queries calculates rem better than media queries, making it possible to change the font-size of the html element and having the queries respond to that change.

Language: css
html {
  container-name: viewport;
  container-type: inline-size;
  font-size: 62.5%;
}

@container viewport (min-width: 25rem) {
  /* Do something */
}

For the most part this is not a big deal in my opinion, as I personally don't change the font-size of the html element (I'm leaving it to the browser to decide what 1rem should be), but it's nice to know that container queries handles this better than media queries.


In conclusion

If you want to go all in on @container for size based queries you can, but you still have to use @media for specific media features, like print, prefers-color-scheme, prefers-reduced-motion, pointer, hover or any of the other media features that exists.