skip to content

Media-queries allow an author to make style changes based on the overall viewport dimensions – but in many cases, authors would prefer styling modular components based on their context within a layout.

warning [Sep 14, 2022]:

The syntax here is out of date. Make sure to use the container query syntax that has actually shipped in browsers.

My proposal builds on David Baron’s @container proposal, which works by applying size & layout containment to the queried elements. Any element with both size & layout containment can be queried using a new @container rule, with similar syntax to existing media-queries.

The approach has been approved by the CSS Working Group, to be added in CSS Containment Level 3, with me as one of the authors.

See the Contain 3 Project for issues and progress.

Establishing Containers

The first step is to establish containers. Any element can become a container, by adding layout, size (generally inline-size), and style containment:

/* Establish containers */
main, aside {
contain: layout inline-size style;
}

This syntax works in the prototype, but is clearly not ideal for readable and clear code. There is an open issue to discuss better syntax for establishing query containers

Note: See the Editor’s Draft Specification for the latest syntax. The Chrome prototype already has basic support for container-type and container-name.

Writing Queries

Each container creates a containment context that can be queried by their descendant elements. We can query the current containment context (the nearest ancestor container) using an @container rule that is very similar to existing @media queries:

/* Change styles according to container size */
@container (min-width: 35em) {
.media {
grid-gap: 1rem;
grid-template: "media content" auto / max-content 1fr;
}
}

The .media class above is now responsive to any container it is in. Each instance of the .media class will query its nearest container.

That means we can have one .media element that moves around, responding to the context we put it in – or multiple .meia elements, each one responding individually to its own location.

Prototype

Chrome has released a prototype in their nightly build. To experiment with the feature, and leave feedback while it is still in development:

  1. Download Chrome Canary,
  2. Go to chrome://flags in the url bar, and
  3. Search for “CSS Container Queries” & enable the experimental feature
  4. Restart the browser

This is a draft prototype and may not match the final design.

Demos & Articles

For a quick introduction, check out:

Or dig into more resources, for the full details: