CSS Container Queries
The same viewport can hold a narrow sidebar and a wide main area. A size container query lets a card follow an ancestor's inline size, not the whole window.
The same viewport can hold a narrow sidebar and a wide main area. A size container query lets a card follow an ancestor's inline size rather than the whole window. Establish containment on the ancestor, then style descendants when that ancestor is wide enough.
container-type and @container
container-type: inline-size makes the element's inline size queryable. The container shorthand can also name the container. A named container helps ensure a rule observes the intended ancestor rather than another nested container.
.catalog { container: lessons / inline-size; }
.card { display: grid; gap: 1rem; }
@container lessons (min-width: 35rem) {
.card { grid-template-columns: 10rem minmax(0, 1fr); }
}Two parents, one card
Place the same card in a sidebar and a main region. Only the instance whose ancestor is wide enough should become two columns. That is the problem media queries cannot describe with a single viewport width. Continue to CSS Grid for the tracks inside each arrangement.
.sidebar, .main { container-type: inline-size; }
@container (min-width: 28rem) {
.card { grid-template-columns: 8rem 1fr; }
}- Name the container when nested queryable ancestors would be ambiguous.
- Test the same component in two differently sized parents.
- Zoom and long content still apply; a query is not a substitute for wrapping.
Size first, then other query types
Style queries and other container features exist, but size queries are the practical starting point for reusable cards. Browser support should be checked for the project. A feature query can wrap an enhancement; the base layout must still work.