CSS Container Queries: Responsive Components, Not Just Pages
Media queries respond to the viewport. But a card might sit in a wide main column on one page and a narrow sidebar on another. Container queries let the card respond to the width of its container instead.
1. Declare a container
.card-wrapper {
container-type: inline-size; /* track this element's width */
container-name: card; /* optional name */
}
2. Query it
.card {
display: grid;
gap: 1rem;
}
@container card (min-width: 480px) {
.card {
grid-template-columns: 160px 1fr; /* image beside text when there's room */
}
}
<div class="card-wrapper">
<article class="card">
<img src="cover.jpg" alt="">
<div>...</div>
</article>
</div>
Now the same card stacks in a narrow sidebar and goes side by side in a wide column, with no extra classes.
Container query units
.card h2 {
font-size: clamp(1rem, 4cqi, 1.75rem); /* 4% of the container's inline size */
}
cqi, cqw, cqh and friends size things relative to the container, which is perfect for fluid typography inside components.
Tips
- An element can't query itself; the container must be an ancestor. That's why a wrapper is common.
inline-sizeis what you want almost always;sizealso tracks height but requires a fixed height.- Use media queries for page layout and container queries for components.
- Supported in all modern browsers.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.