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.

Open
The wide slot lays the card out in two columns with a larger heading. Make the frame narrower until that slot is under 30rem: it becomes the narrow card.
Code CSS · 10 lines
.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 2 reasons · 6 rules · support · credits

Why it works

  1. The query measures the nearest container, so the same card is right in a sidebar and in a wide column.
  2. 1cqi is 1% of that container's inline size. The clamp() math from Fluid sizes with clamp() carries over, per component.

Rules

  1. The container must be an ancestor. An element cannot query itself.
  2. A container cannot take its width from its content. Never put container-type on a shrink-to-fit element, or it collapses to zero.
  3. With no container ancestor the query never matches. Kevin Powell makes header, main and footer containers in his reset, so most components need none of their own.
  4. A container cannot also be a subgrid. Subgrid rows shared across cards and this entry need separate elements.
  5. Container units are different from queries. With no container above the element, cqi measures the viewport, so one token written with cqi serves the page and every slot.
  6. Never register a fluid token that uses cqi with @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