Course contentsShow
← Web Development
Lesson 434 of 2,9827. Responsive DesignFree lesson

Container Query Units (cqw, cqh, cqi, cqb)

Using container-relative units for fluid sizing that scales with the container rather than the viewport.

Container Query Units (cqw, cqh, cqi, cqb)

You'll learn: How to size elements relative to their container's dimensions instead of the viewport.

What Are Container Query Units?

Just like viewport units (vw, vh) let you size things relative to the browser window, container query units let you size things relative to a specific container you've defined. This means your component's typography, spacing, and sizing can all scale with the container they're inside—not just the entire screen.

Think of it like this: viewport units are like measuring your furniture based on the size of your entire house. Container query units are like measuring your furniture based on the size of the room it's actually in. Much more practical!

The Four Container Query Units

Once you've set up a container context (using container-type), these units become available:

  • cqw — 1% of the container's width
  • cqh — 1% of the container's height
  • cqi — 1% of the container's inline size (width in horizontal languages)
  • cqb — 1% of the container's block size (height in horizontal languages)

Why Use Them?

These units make your components truly modular. A card component can have font-size: 4cqw; and automatically scale perfectly whether it's in a narrow sidebar (small font) or a wide main section (larger font)—all without media queries.

.card {
  container-type: inline-size;
}

.card h2 {
  font-size: clamp(1rem, 5cqw, 2rem);
  padding: 2cqi;
}

The heading and padding now scale with the card's width, creating fluid, self-contained components.

Key Takeaway: Container query units (cqw, cqh, cqi, cqb) let you size elements relative to their container's dimensions, making truly responsive components that adapt to their context rather than just the viewport.