Container Queries
Prerequisites: Responsive design and media queries
Media queries ask about the viewport. But a card component might sit in a narrow sidebar on one page and a wide main column on another. Container queries let a component respond to the size of its container.
.card-wrapper {
container-type: inline-size;
container-name: card;
}
.card {
display: grid;
gap: 1rem;
}
@container card (width >= 30rem) {
.card {
grid-template-columns: 10rem 1fr;
}
}
container-type: inline-sizemakes an element a container you can query by width. (It applies size containment in that direction: the container's width can no longer depend on its children.)container-nameis optional; unnamed@containerqueries use the nearest container ancestor.- The shorthand is
container: card / inline-size. - A container can't query itself — only its descendants change.
Proving it
<style>
.wrap { container-type: inline-size; }
.narrow { width: 300px; }
.wide { width: 700px; }
.card { display: block; }
@container (width >= 30rem) {
.card { display: grid; grid-template-columns: 10rem 1fr; }
}
</style>
<div class="wrap narrow"><div class="card"><img src="a.jpg" alt="" width="10" height="10"><p>Text</p></div></div>
<div class="wrap wide"><div class="card"><img src="a.jpg" alt="" width="10" height="10"><p>Text</p></div></div>
<script>
for (const card of document.querySelectorAll(".card")) {
console.log(card.parentElement.className, getComputedStyle(card).display);
}
</script>
wrap narrow block
wrap wide grid
Same component, same viewport — different layouts, because the containers differ.
Container query units
Inside a container, cqi is 1% of the container's inline size (cqb
for block size):
.card h2 { font-size: clamp(1.1rem, 4cqi, 1.8rem); }
Style queries
@container style(--variant: featured) queries a custom property's
value on the container. Size queries work in every major browser
(Chrome and Edge 105, Safari 16, Firefox 110); style queries on
custom properties are newer (Firefox added them last, in version 151).
When to use which
- Media queries for page-level layout and user preferences.
- Container queries for reusable components.
(The W3C validator used for this course doesn't know container queries yet and flags them — one of the rare cases where the validator is behind the browsers.)