Sub topic 2
Naming Containers and Using Container Units
Assume you know CSS selectors, the cascade, media queries, custom properties, and basic grid or flexbox.
Naming Containers and the Container Shorthand
A query container is an ancestor whose size can control styles on its descendants. Give it a name and a containment type with the container shorthand:
.card-wrapper {
container: card / inline-size;
}
.card {
display: block;
}
@container card (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}container: card / inline-size is equivalent to:
.card-wrapper {
container-name: card;
container-type: inline-size;
}The rule applies to .card, a descendant of .card-wrapper. A container query does not style the container based on its own query.
Container Query Units
Container query units measure a query container rather than the viewport.
| Unit | Meaning |
|---|---|
| `cqi` | 1% of the container's inline size |
| `cqb` | 1% of the container's block size |
| `cqw` | 1% of the container's width |
| `cqh` | 1% of the container's height |
| `cqmin` | 1% of the smaller relevant dimension |
| `cqmax` | 1% of the larger relevant dimension |
cqi and cqb follow writing direction. They are usually safer than physical width and height units for components that support different writing modes.
Fluid Type and Spacing
Use cqi to scale a component inside its available space. Use clamp() to keep the result within readable limits:
.card {
padding: 2cqi;
}
.card h2 {
font-size: clamp(1.125rem, 4cqi, 2rem);
}Units Without a Container
If no eligible query container exists, container query units use the small viewport as their fallback. For example, cqw behaves like svw, and cqh behaves like svh. This prevents the units from becoming invalid, but the result may no longer describe the component's actual size.
Which Container Is Used?
A query normally uses the nearest eligible ancestor. A named query uses the nearest ancestor with that name. Nested containers therefore require careful naming. Container units generally resolve against the nearest eligible query container for the styled element.
Exercise
Which unit represents 1% of a container's inline size, and what does it use when no container applies?
Show answer
cqi represents 1% of the container's inline size. Without an eligible container, it falls back to the small viewport's inline size.