Container queries
Components that adapt to their space
Lesson 4 of 20 · 12 min · Module 1: Layouts that adapt
A media query looks at the whole screen, but a card does not know whether it sits in a wide main column or a narrow sidebar. Container queries let a component respond to the space it actually has.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Turn an element into a query container
- Write @container rules
- Choose between media queries and container queries
The idea
Mark an element as a container with container-type: inline-size. Inside it, @container (min-width: 400px) { … } applies only when that container is at least 400px wide. The same card can then be horizontal in the main column and stacked in the sidebar, on the same screen.
.sidebar { container-type: inline-size; }
@container (min-width: 300px) {
.widget { display: flex; }
}
01Containers measure themselves
container-type: inline-size tells the browser to track the element’s width so its descendants can query it. A container cannot style itself with its own query, which prevents endless loops.
02The nearest container answers
@container (min-width: 400px) checks the closest ancestor that is a container. When containers are nested, give them names and query a specific one.
.sidebar { container: sidebar / inline-size; }
@container sidebar (max-width: 250px) {
.card h2 { font-size: 16px; }
}
03Media or container?
Use media queries for page-level decisions, such as switching the whole layout to one column. Use container queries for components that appear in different places: cards, widgets and form groups.
Your turn
.main and .sidebar containers with container-type: inline-size. Then, inside @container (min-width: 400px), give .card display: grid, grid-template-columns: 120px 1fr and gap: 12px. On an 800px screen the main card turns horizontal while the sidebar card stays stacked; on a phone both are stacked.What the checks look for
- The main column is a container
- The sidebar is a container
- At 800px the main card becomes a grid
- Its two columns are 12px apart
- On the same screen the sidebar card stays stacked
- On a phone the main card is stacked too
Take this with you
Container queries let components respond to their own space, not to the screen.
Go a little further
Use a container query unit: give the card title font-size: clamp(16px, 5cqi, 22px) so it scales with the container width.