Sub topic 2
The container query idea
A container query lets an element change its styles based on the size of an ancestor element instead of the size of the viewport. This chapter explains the model: what a query container is, who queries whom, and why the browser asks you to opt in. The next chapters cover the syntax in detail.
Prerequisites
This chapter assumes you can:
- Read and write CSS selectors and understand the cascade and the box model.
- Build layouts with flexbox or grid.
- Write
@mediaqueries for responsive design. - Use CSS custom properties.
The question a component needs answered
A viewport media query answers this question: "How wide is the browser window?" A reusable component usually needs to answer a different one: "How much room do I have here?"
Take a product card. On a wide page it sits in a three-column grid, where each column might be 300px wide. In a sidebar on the same page it might get 240px. In a full-width hero section it might get 900px. The viewport is identical in all three cases, so a media query cannot tell the card apart. You end up writing selectors tied to page regions, such as .sidebar .card, and the component stops being self-contained.
Container queries move the measurement. The component asks about the box it lives in, and the answer follows the component wherever you place it.
Two roles: the container and the query target
Every container query involves two elements with distinct roles.
- The query container is an ancestor that you have marked as something other elements can query. The browser measures it.
- The query target is a descendant whose styles depend on that measurement. Styles inside an
@containerrule apply to it.
Here is the smallest complete example. The HTML has a wrapper and a card inside it:
<div class="card-wrapper">
<article class="card">
<img src="photo.jpg" alt="A mountain lake" />
<div class="card-body">
<h2>Mountain lake</h2>
<p>A quiet spot two hours from the trailhead.</p>
</div>
</article>
</div>The CSS declares the wrapper as a container and styles the card based on the wrapper's width:
.card-wrapper {
container-type: inline-size;
}
.card {
display: grid;
gap: 1rem;
}
@container (min-width: 400px) {
.card {
grid-template-columns: 8rem 1fr;
}
}The .card-wrapper rule marks the wrapper as a query container. The @container rule then says that when the nearest query container is at least 400px wide, the card becomes a two-column grid. The viewport can be 320px or 3000px wide. If the wrapper is 400px or wider, the card uses two columns.
The .card rule inside @container styles a descendant of the container. This is the central constraint of the feature, covered next.
An element cannot query itself
A container query can style the descendants of a container but never the container itself. If the wrapper in the example had grid-template-columns inside its own @container rule, that rule would never apply.
The reason is a circular dependency. Consider an element with width: fit-content whose children are styled by its own width:
- The browser needs the element's width to evaluate the query.
- The query result changes the children's styles.
- The children's styles change their size.
- The children's size determines the element's width.
Step 4 feeds back into step 1, and the browser could loop forever or flicker between two states. Media queries avoid this because the viewport size does not depend on anything inside the page. Container queries need a different guarantee, and the container declaration provides it.
Containment: the guarantee that breaks the loop
When you set container-type on an element, you opt that element into CSS containment. Containment is a promise that the element's layout does not depend on certain things inside it.
With container-type: inline-size, the element applies inline-size containment. Its inline size (its width in horizontal writing modes) can no longer be computed from its contents. The browser can therefore work out the container's width first, using only its parent and its own styles. Only then does it evaluate queries and style the descendants. There is no loop because the order of work is fixed.
The block size (the height in horizontal writing modes) is still free to grow with its content. That is why inline-size is the usual choice, since most components need to respond to width and still grow taller as content is added.
This promise has costs. A container can collapse to zero width if nothing else gives it a width, because its children no longer contribute. A later chapter covers these side effects. For now, remember that containment is the reason the opt-in exists.
Why you opt in instead of querying any ancestor
It might seem simpler if every element were automatically queryable. That design would impose containment on the whole page. Every box would have a width that ignores its contents, and ordinary shrink-to-fit layouts such as inline-blocks, floats, and auto-width flex items would break.
Making it opt-in keeps the cost where it is useful. You pick the few elements that should act as containers, typically the wrapper around a component or a layout region such as a main column, a sidebar, or a grid cell.
How the browser picks the container
An @container rule does not say which element to measure. For an unnamed query, the browser starts at the target element and walks up the ancestor chain. It uses the nearest ancestor that is a suitable query container.
This means the same rule can produce different results for the same component in different places:
.sidebar,
.main {
container-type: inline-size;
}
.card {
display: block;
}
@container (min-width: 400px) {
.card {
display: flex;
gap: 1rem;
}
}A card inside .sidebar is measured against the sidebar. A card inside .main is measured against the main column. The CSS for .card is the same in both places, and only the surrounding space differs. When containers are nested, the nearest one wins. A later chapter shows how names make the choice explicit.
Media queries and container queries compared
| Aspect | Media query (`@media`) | Container query (`@container`) |
|---|---|---|
| What it measures | The viewport, or device features | An ancestor element you declared as a container |
| Opt-in required | No | Yes, through `container-type` |
| Can style the measured element itself | Not applicable | No, only descendants |
| Same component in different layout slots | Gets one answer for all slots | Gets a separate answer per slot |
| Works for | Page-level decisions | Component-level decisions |
Using both together
Container queries do not replace media queries. They handle different concerns.
Use media queries for conditions that belong to the viewport or the user's environment. Examples are prefers-reduced-motion, prefers-color-scheme, print, and the overall page layout, such as when the sidebar moves below the main content.
Use container queries for decisions inside a component about how it arranges itself in the space it was given.
A common pattern has the page layout change on a media query, which changes how wide the slots are. Components then adapt to the new slot widths through container queries. The page does not need to know anything about the components inside it.
Common misconceptions
- "A container query measures the element it styles." It measures an ancestor. The styled element and the measured element are different elements.
- "Any wrapper counts automatically." A wrapper only counts once it has a
container-typethat supports the query. - "The container can restyle itself when it gets wider." It cannot, because of the circular dependency. Put the styled elements one level down, or wrap the element you want to style in a new container.
- "Container queries make media queries obsolete." Viewport and user-preference conditions still need
@media.
What comes next
You now have the model: an ancestor is declared as a container, the browser measures it, and descendants adapt. The next chapter looks at container-type itself, including its values and what each one contains. After that you will write @container rules with fuller conditions, name your containers, and see how queries resolve when containers are nested.
Exercise
A developer writes .panel { container-type: inline-size; } and then, inside @container (min-width: 500px), writes .panel { padding: 2rem; }. The panel is 700px wide, but the padding never changes. Why, and how could the developer fix it?
Show answer
The @container rule targets .panel, which is the query container itself. A container query only styles descendants of the container, so the rule never applies to the element it measures. The fix is to put the padding on a descendant, for example by wrapping the content in an inner element such as .panel-content and styling that inside the @container rule, or by adding a new outer wrapper with container-type: inline-size and querying it from .panel.
Exercise
The same .card component appears in a 280px sidebar and a 720px main column. Both .sidebar and .main have container-type: inline-size, and the stylesheet has one rule, @container (min-width: 400px) { .card { display: flex; } }. Which card uses display: flex, and why?
Show answer
Only the card in the main column. An unnamed @container rule is evaluated against the nearest suitable ancestor container. The card in the sidebar is measured against the 280px sidebar, so the condition fails. The card in the main column is measured against the 720px column, so the condition passes. The component CSS is the same in both places, and the surrounding space decides the result.
Exercise
Explain in two or three sentences why the browser requires container-type instead of treating every element as a query container.
Show answer
Querying an element's size requires that the element's size does not depend on its own descendants, otherwise styles could change the size and the size could change the styles in a loop. container-type applies containment, which removes that dependency for the chosen axis. Applying it to every element would break shrink-to-fit sizing across the page, so the browser asks you to opt in only where you need it.