Container queries enable us to style an element depending on the size of its parent — a crucial difference from media queries, which only query the viewport. This has long been a problem for responsive design, as often we want a component to adapt to its context.Think of a card which might be shown in a wide content area or a narrow sidebar. We’d probably want to show something more akin to the card’s mobile layout in the sidebar, while perhaps showing style when there is sufficient horizontal space. But media queries aren’t aware of the component’s context. For this reason, container queries have been on many a developer’s wish list for some time.
For a container query, we need to specify an element as our container, using the container property (shorthand for container-type and container-name). The container-type can be width, height, inline-size or block-size. inline-size and block-size are logical properties, which may produce different results according to the document’s writing mode.
Then we can use the @container at-rule in a way that’s similar to a media query. Note the different way the rule can be expressed within the brackets (inline-size > 30em rather than min-width: 30em). This is part of the Media Queries Level 4 specification. For the card layout example above, when the container is wider than 30rem we switch to a horizontal layout using flexbox:
The CSS Containment Level 3 specification is currently in working draft, which means the syntax could change at any point — in fact, it’s changed since some articles on container queries were published on it last year. The examples here are in line with the proposed syntax at the time of writing.