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:
- Download Chrome Canary,
- Go to
chrome://flags
in the url bar, and - Search for “CSS Container Queries” & enable the experimental feature
- Restart the browser
This is a draft prototype and may not match the final design.
Demos & Articles
For a quick introduction, check out:
- Container Queries: a Quick Start Guide by David Herron
- My collection of codepen demos
Or dig into more resources, for the full details:
- MDN Documentation by Rachel Andrew
- Container Queries are actually coming by Andy Bell
- Say Hello To CSS Container Queries
by Ahmad Shadeed
(Annotated on CSS Tricks by Robin Rendle) - CSS Container Queries: A First Look + Demo by Bramus Van Damme
- Awesome-Container-Queries by Stuart Robson