Sub topic 3
Container Query Units (cqi, cqw, and Friends)
This chapter assumes you know CSS selectors, custom properties, flexbox or grid, and basic @media queries.
Container query units
Container query units scale from a query container rather than the viewport:
cqi: 1% of the container’s inline size.cqw: 1% of its width.cqb: 1% of its block size.cqh: 1% of its height.cqminandcqmax: the smaller or larger of the inline and block dimensions.
Use them when content should scale with the component’s available space.
.card-wrapper {
container-type: inline-size;
}
.card {
padding: clamp(1rem, 3cqi, 2rem);
}
.card h2 {
font-size: clamp(1rem, 4cqi, 2rem);
}cqi is often the most useful unit because it follows the writing direction’s inline axis.
Putting it together: a component that adapts to its space
A card can switch from a stacked layout to a two-column layout wherever it is placed.
.card-wrapper {
container: card / inline-size;
}
.card {
display: grid;
gap: 1rem;
}
@container card (min-width: 30rem) {
.card {
grid-template-columns: 8rem 1fr;
}
}The same card can therefore work in a narrow sidebar and a wide content area without viewport-specific breakpoints.
Style queries on custom properties
Style queries test a computed custom property on an ancestor. They are useful for themes or component modes.
.theme-scope {
--theme: dark;
}
@container style(--theme: dark) {
.card {
background: #222;
color: #eee;
}
}Browser support and progressive enhancement
Keep a usable default style, then add container-query behavior inside @supports.
.card {
display: block;
}
@supports (container-type: inline-size) {
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
}
}
}Debugging and common pitfalls
- The query may match the nearest eligible ancestor, not the ancestor you expected. Name containers when several exist.
- A size query cannot measure an ancestor’s size if that ancestor is not declared as a suitable container.
- Height conditions need the relevant block-axis containment, such as
container-type: size. - Check computed styles and the browser’s container overlay when available.
- Remember that containment can affect sizing and layout. Test intrinsic content, overflow, and percentage sizes.
Exercise
What unit would you use to make a heading scale with a component’s inline size?
Show answer
Use cqi, such as font-size: clamp(1rem, 4cqi, 2rem);.