Entry 05
Container queries with container units
Use it for any component that appears in slots of different widths. The component responds to the space it is given, where a media query only knows the viewport.
Code
.slot { container-type: inline-size; }
.card h2 { font-size: clamp(1.25rem, 1rem + 2cqi, 2rem); }
@container (width > 30rem) {
.card {
display: grid;
grid-template-columns: 12rem 1fr;
}
}Why it works, the rules and the credits
Why it works
- The query measures the nearest container, so the same card is right in a sidebar and in a wide column.
1cqiis 1% of that container's inline size. Theclamp()math from Fluid sizes withclamp()carries over, per component.
Rules
- The container must be an ancestor. An element cannot query itself.
- A container cannot take its width from its content. Never put
container-typeon a shrink-to-fit element, or it collapses to zero. - With no container ancestor the query never matches. Kevin Powell makes
header,mainandfootercontainers in his reset, so most components need none of their own. - A container cannot also be a subgrid. Subgrid rows shared across cards and this entry need separate elements.
- Container units are different from queries. With no container above the element,
cqimeasures the viewport, so one token written withcqiserves the page and every slot. - Never register a fluid token that uses
cqiwith@property. A registered length computes once on:root, where there is no container, and every slot then gets the viewport's value.
Support
- Chrome
- 105
- Firefox
- 110
- Safari
- 16
Credits
Borrowed from: Kevin Powell, Improve your reset with these modern CSS additions, 2024-09-04 · Una Kravets, Container queries land in stable browsers, 2023-02-14 · Josh W. Comeau, A Friendly Introduction to Container Queries, 2024-11-04 · Stephanie Eckles, Container Query Units and Fluid Typography