Container Queries (@container)
What is a Container Query?
Imagine designing a weather card component. If you place the card in a wide main dashboard column, it should display horizontal layouts with side-by-side text and icons. If you place the exact same card in a narrow sidebar column, it should stack vertically to fit.Traditional media queries only check the width of the entire screen. A Container Query allows an element to query the width of its direct parent container instead, altering its styles based on how much space its parent box provides:
container-type: inline-size; โ Declares that the parent element acts as a container query anchor.@container (max-width: 400px) โ Applies styles to child elements if the container parent is 400px or narrower.Why does it matter?
Container queries are the holy grail of component-driven web design. They allow you to build fully self-contained, modular widgets that rearrange their layouts automatically depending on *where* you place them on the page.Syntax Breakdown
1. Mark the parent container:.card-parent {
container-type: inline-size;
}
2. Query the parent:
@container (max-width: 400px) {
.card-child {
flex-direction: column;
}
}
Common Mistakes
@container rules but forget to define container-type: inline-size; on the parent container class, the browser won't track the parent's size and the styles won't trigger!Quick Reference
@container โ Applies styling rules based on parent container width.container-type: inline-size โ Declares container query boundaries on the parent.Your Task
Set the `container-type` property of the `.card-parent` class to `inline-size` to allow nested components to query its size.
index.html
Type code above to start the lesson.
Live Preview