Sub topic 10
Putting it together: a component that adapts to its space
This chapter combines the pieces from earlier chapters into one reusable card component. You should already know how to declare a container with container-type, write @container rules with range syntax, and name a container. You should also be comfortable with grid layout and with clamp().
The goal is a card that you can drop into a narrow sidebar, a main column, or an auto-fill grid. It lays itself out correctly in each place, with no per-page overrides and no viewport media queries.
Plan the component before writing CSS
Start by deciding which layouts the card needs and what each one depends on. With viewport queries you would guess at these widths from the page layout. With container queries you describe the card's own needs.
| Layout | Container width | Arrangement |
|---|---|---|
| Stacked | under 28rem | Image on top, text below, action below the text |
| Side by side | 28rem up to 44rem | Small image left, text and action in the right column |
| Wide | 44rem and up | Image, text, and action in three columns |
The breakpoints belong to the component, so they live next to the component's styles. A page author who places the card never needs to know them.
The markup
The card needs a wrapper element. A container cannot query itself, because @container rules only apply to descendants of the container. So the wrapper is the container and .card is the element being styled.
<div class="page">
<aside class="sidebar">
<div class="card-wrapper">
<article class="card">
<img class="card-image" src="trail.jpg" alt="A mountain trail at sunrise" width="640" height="480">
<div class="card-body">
<h2 class="card-title">Ridge Trail</h2>
<p class="card-text">A 12 km loop with steady climbs and wide views of the valley.</p>
</div>
<a class="card-action" href="/trails/ridge">View trail</a>
</article>
</div>
</aside>
<main class="card-grid">
<div class="card-wrapper">
<article class="card">
<img class="card-image" src="lake.jpg" alt="A calm lake at dusk" width="640" height="480">
<div class="card-body">
<h2 class="card-title">Lake Loop</h2>
<p class="card-text">An easy 5 km walk around the lake, suitable for families.</p>
</div>
<a class="card-action" href="/trails/lake">View trail</a>
</article>
</div>
</main>
</div>The component styles
Write the stacked layout first, as the base styles with no query. This is the mobile-first habit applied to containers: the narrowest layout is the default, and queries add complexity as space grows.
.card-wrapper {
container: card / inline-size;
}
.card {
display: grid;
gap: 1rem;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 0.5rem;
}
.card-image {
width: 100%;
height: auto;
aspect-ratio: 4 / 3;
object-fit: cover;
}
.card-title {
margin: 0;
font-size: clamp(1.125rem, 5cqi, 1.75rem);
}
.card-text {
margin: 0.5rem 0 0;
}
.card-action {
justify-self: start;
}
@container card (width >= 28rem) {
.card {
grid-template-columns: 9rem 1fr;
align-items: start;
}
.card-action {
grid-column: 2;
}
}
@container card (width >= 44rem) {
.card {
grid-template-columns: 12rem 1fr auto;
align-items: center;
padding: 1.5rem;
}
.card-action {
grid-column: auto;
justify-self: end;
}
}Each part of this stylesheet has a job.
container: card / inline-sizesets the name and the type in one declaration. Only the inline axis is contained, so the wrapper's height still comes from the card inside it.- The base
.cardrule is the stacked layout. A browser without container query support shows this layout and nothing breaks. - The two
@container cardrules use range syntax with>=. Both name the container, so a future ancestor with a different container name cannot capture them by accident. - The wide rule comes after the medium rule and has the same specificity, so it overrides the properties they share. That is why it resets
grid-columntoauto. Without the reset, the action would stay in column 2 and the third column would hold nothing. - The title uses
5cqi, which is 5% of the wrapper's inline size, withclamp()limiting the result. At a 20rem container the value would be below the minimum, so the title sits at 1.125rem. At 35rem or wider it reaches the 1.75rem cap. Between those widths it scales smoothly with the container.
Placing the component
Now the page layout. None of these rules mention the card's internal layout.
.page {
display: grid;
grid-template-columns: minmax(14rem, 20rem) 1fr;
gap: 2rem;
}
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));
gap: 1rem;
}The sidebar column is at most 20rem wide, so the sidebar card stays stacked. The grid cells are at least 18rem wide and grow with the space, so the grid cards switch to the side-by-side layout when a cell reaches 28rem. Resize the window and watch: the sidebar card stays stacked at every window size, and the grid cards change layout as the cell widths change. A viewport media query could not do this, because the viewport width says nothing about how much room a given card has.
Test the component outside the page
A component that depends only on its container is easy to test in isolation. Wrap it in a fixed-width element and check each layout in turn:
<div style="width: 18rem"><div class="card-wrapper">...</div></div>
<div style="width: 32rem"><div class="card-wrapper">...</div></div>
<div style="width: 50rem"><div class="card-wrapper">...</div></div>Put these three on one test page and you can see all three layouts at once without resizing the browser. This is a practical advantage of container queries: a style guide or a test page can show every state side by side.
Edge cases to check
The container's own width must not come from its content
inline-size containment means the wrapper ignores its children when computing its width. As a normal block it fills the available width, so this is fine. If you make the wrapper a flex item or a grid item with auto sizing, it can shrink to zero width, because there is no content-based size to fall back on. Give such wrappers an explicit width, flex: 1, or a grid track that sizes them.
A container that sits inside a changing parent
If the card's width depends on its parent, and the card's layout changes the parent's width, you can create a loop. For example, a card in a max-content column changes layout, which changes its own contribution to the column width. Browsers prevent infinite loops, but the result can be a layout that does not settle on the value you expect. Keep container widths determined by the surrounding layout, not by the component's output.
Query the right container
An unnamed @container rule matches the nearest ancestor that is a container of any size-querying type. If a developer later adds container-type: inline-size to some element between the wrapper and the card, an unnamed rule silently switches to that element. Naming the container, as this component does, makes the dependency explicit.
Do not query a container for properties it cannot provide
The wrapper uses inline-size, so conditions on height never match. If a component needs height-based rules, use container-type: size. Then the wrapper must also have a height that does not come from its content, or it collapses.
Fallback for older browsers
The base styles already give unsupported browsers a usable stacked card. If you also want to avoid applying container-type where it is not understood, wrap the container declaration and the @container rules in @supports (container-type: inline-size), as covered in the support chapter. For this component the plain base styles are enough, because the container declaration and queries are ignored together.
Common mistakes
- Putting
container-typeon.cardand styling.cardin the query. A rule cannot style the container it queries. Add a wrapper, or query an ancestor of the styled element. - Using
vworvhinside the component. These tie the component back to the viewport. Usecqior relative units instead. - Setting different breakpoints in the page CSS. Overrides in page-level files defeat the purpose. If a card needs a different layout in one place, change the container width or add a documented modifier class.
- Forgetting that
cqifalls back to the viewport. If no ancestor is a size container, container units resolve against the small viewport size. A title that looks wrong everywhere can mean the wrapper lost itscontainer-type.
Exercises
Exercise
A card sits in a column that is 24rem wide. The wrapper is container: card / inline-size. Which layout does the card use, and what is the computed title size, given font-size: clamp(1.125rem, 5cqi, 1.75rem) and a 16px root font size?
Show answer
The width is below 28rem, so the card uses the stacked layout. The container is 24rem, which is 384px, so 5cqi is 19.2px. That is above the 18px minimum (1.125rem) and below the 28px maximum (1.75rem), so the title is 19.2px.
Exercise
You change the wide rule to @container card (width >= 44rem) but forget to reset grid-column in .card-action. The card is placed in a 50rem container. What goes wrong visually, and how do you fix it?
Show answer
The action stays in grid-column: 2 from the medium rule, so it sits in the middle column under the text, and the third auto column stays empty. Add grid-column: auto; (and justify-self: end;) to .card-action inside the wide rule so the action moves into the third column.
Exercise
Why does the sidebar card stay stacked at every window size, while the grid cards change layout as the window grows?
Show answer
Container queries use the width of the wrapper, not the viewport. The sidebar column is capped at 20rem, so its wrapper never reaches 28rem. The grid cells grow with the available space, so their wrappers can reach 28rem and then 44rem.