A container is a specific ancestor element whose size or styles provide the reference for querying a descendant. It may be the descendant’s parent or another element higher in the DOM tree. Container queries make this relationship useful for reusable modules: a component can adapt to the space available around it instead of responding only to the viewport. section 10.0
Use containers deliberately when building responsive, modular CSS:
- Define a size-query container with container-type, optionally giving it a container-name; the container shorthand sets both values together. section 10.1.1
- Query the defined container with @container, then change descendant styles when its inline size meets a condition such as width >= 450px. section 10.1.1
- Define containing elements that may hold other modules as containers, allowing nested modules to respond to their immediate layout context. section 10.2.3
- Prefer an existing containing element over an extra wrapper when possible; adding a dedicated module container works but introduces additional markup. section 10.2.3
A media module that responds to its container
Define the layout element as an inline-size container, then make the media component switch to a horizontal flex layout only when that container is at least 450px wide:\n\n.l-page > * {\n container: layout / inline-size;\n}\n\n@container layout (width >= 450px) {\n .media {\n display: flex;\n gap: 1.5rem;\n }\n}\n\nThe same module can therefore work in a wide main column or a narrow sidebar without relying on the viewport width. section 10.1.1 section 10.0
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;
}
}
}
Inspect the complete layout and media-module example, including the container declaration and @container rule. section 10.1.1


























