A module can have plenty of room on a wide page but little room inside a narrow sidebar. A viewport-based media query cannot distinguish those situations. Set container-type on an ancestor to make its available size queryable, then use @container to change the module’s layout when that ancestor meets a size condition. section 10.1.1
Listing 10.3 Adding container queries
@layer layout {
.l-page {
margin-inline: 1rem;
}
.l-page > * {
container: layout / inline-size; #1
}
@media (min-width: 800px) {
.l-page {
display: grid;
gap: 1rem;
grid-template-columns: 1fr 30%;
}
}
}
@layer modules {
.media {
padding: 1.5rem;
background-color: #eee;
border-radius: 5px;
}
.media__image {
margin-inline: auto;
}
@container layout (width >= 450px) { #2
.media {
display: flex;
gap: 1.5em;
}
.media__image {
align-self: start;
margin-inline: revert;
}
}
}
Here, each direct child of the page layout becomes a named inline-size container. The media module switches to a horizontal flex layout when its container is at least 450 px wide. A separate media query still controls the page grid; the module’s breakpoint follows its available space instead. section 10.1.1
Choose the type according to the dimension you need to query:
- normal is the initial value. It does not establish a container for size queries. section 10.2.1
- inline-size permits queries against the inline dimension, typically width, while the container’s height can still follow its contents. It suits most width-responsive modules. section 10.2.1
- size establishes a container for size queries in both dimensions. With either size-querying type, children cannot determine the container’s size in a measured dimension. section 10.2.1 section 10.5
That sizing restriction prevents a feedback loop: a query must not change the very container size that decides whether it matches. Normal document flow often gives a block-level container a known width. A flex item may instead need a flex-basis or flex-grow value to establish one. Setting container-type applies the necessary containment without usually requiring a separate contain rule. section 10.2.1
A name is optional with container-type: inline-size; an unnamed @container query uses the nearest ancestor that is a container. For a specific ancestor, add container-name and use that name in the query: the browser skips nearer containers whose names do not match. The shorthand container: layout / inline-size sets both properties, but requires a name. section 10.1.1 section 10.2.2
Define containers consistently around reusable modules, including places where modules can nest. Making a media module’s body a container lets a module inside it respond to that smaller region; flex-grow gives the body a known width. An extra wrapper can also supply a container, but adds markup. Use container queries for module-level adaptation and retain media queries where the page layout itself depends on the viewport. section 10.2.3 section 10.1.1
