Size text with container query units
Set container-type on a wrapper and size headings in cqi so the same card scales in a wide column and a narrow one.
You sized a card heading in vw so it grows with the page. Then you dropped the same card into a sidebar and the heading is still sized for the full viewport, so it wraps onto three lines. Viewport units know nothing about the column the card sits in.
Container query length units do. 1cqi is 1% of the inline size of the nearest query container. A heading sized in cqi follows the box it is in, wherever you put that box.
Make the card a container
The units only resolve against an element whose container-type is size or inline-size. I use inline-size: it contains the inline axis and lets the card grow along the block axis. In horizontal writing, those axes are width and height.
.card {
container-type: inline-size;
}
.card h2 {
font-size: clamp(1rem, 6cqi, 2.5rem);
}Each heading now takes 6% of its card’s inline size, held between 1rem and 2.5rem.
Check the numbers
Add these grid rules and put two cards in an 864px-wide test area with a 16px root font size.
<style>
.grid { display: grid; grid-template-columns: 2fr 1fr; gap: 24px; width: 864px; }
</style>
<div class="grid">
<div class="card"><h2>Wide card</h2></div>
<div class="card"><h2>Narrow card</h2></div>
</div>The tracks are 560px and 280px wide. At 6cqi, their heading sizes are 33.6px and 16.8px.
The six units
MDN lists six. cqw and cqh are 1% of the container's width and height.
cqi and cqb are 1% of its inline and block size, which in a horizontal writing mode are the same two numbers. cqmin and cqmax take the smaller or the larger of cqi and cqb.
Use cqi when the size should follow the writing mode. cqb needs a container with block-size containment (container-type: size). For cqw and cqh, the eligible ancestor depends on which physical axis it contains.
Without a query container as an ancestor, the unit falls back to the small viewport unit for that axis, svi for cqi. A forgotten container-type does not throw or go to zero. The heading goes back to scaling with the viewport, which is the bug you started with, so check the computed size once.