Container Query Units in Practice — cqw, cqh, cqi, cqb
Apply CSS container query length units (cqw, cqh, cqi, cqb, cqmin, cqmax) for fluid sizing — practical recipes for typography, spacing, and dimensions inside containers.
Detailed Explanation
Container Units, Recipe by Recipe
The CSS container query length units are simple to define but require practice to use well. This guide focuses on practical recipes rather than the unit definitions themselves.
Recipe 1: Fluid Headings Without Media Queries
.text-host {
container-type: inline-size;
}
.headline {
font-size: clamp(1.25rem, 5cqi, 2.75rem);
line-height: 1.15;
}
5cqi means "5% of the container's inline size". On a 320px host the heading is 16px, on a 1200px host it's 60px (capped at 44px by clamp()'s max). One declaration replaces three media queries.
Recipe 2: Padding That Grows With the Card
.card {
padding: clamp(0.75rem, 3cqi, 1.75rem);
}
A 280px card gets ~12px padding (clamped at the minimum); a 600px card gets 18px; a 1000px card gets 28px (clamped at the maximum). The card always feels appropriately spaced regardless of host.
Recipe 3: Aspect-Ratio Avatars at Any Size
.avatar {
width: clamp(36px, 8cqi, 96px);
aspect-ratio: 1;
border-radius: 50%;
}
The avatar scales smoothly between 36px and 96px depending on container width.
cqi vs cqw: Which to Use?
cqw: 1% of container's physical width, regardless of writing mode.cqi: 1% of container's inline size (width in horizontal writing modes, height in vertical).
For UIs that may be localized into vertical scripts (Japanese, Mongolian), prefer cqi. For pure CSS demos and ASCII-only content, cqw is fine.
cqmin and cqmax for Square-ish Things
.square-icon {
width: 8cqmin;
height: 8cqmin;
}
cqmin always refers to the smaller dimension, so the icon never grows past what the container can fit in its narrowest direction.
Setup Reminder
Container query units require an ancestor with container-type: inline-size (or size for cqh/cqb). Without it, the units silently resolve to 0.
Combining With Real Pixels
.title {
font-size: clamp(1rem, 1rem + 2cqi, 2rem);
}
The 1rem + 2cqi middle value gives a stable base size (1rem) plus a fluid component, ensuring text is never absurdly small in narrow hosts.
Use Case
Use container query units when you want continuous fluid scaling without writing breakpoints — ideal for design-system primitives like buttons, cards, and typography that ship to teams who place them in wildly different contexts.