Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to use container queries

Short answer

Declare the parent a container and write conditions with @container. The card below sits in a narrow and a wide column:

<style>
  .slot { container-type: inline-size; margin-bottom: 8px; border: 1px dashed silver; }
  .card { display: grid; gap: 8px; padding: 8px; }
  .card img { width: 100%; }
  @container (min-width: 300px) { .card { grid-template-columns: 100px 1fr; } }
</style>
 
<div class="slot" style="width: 200px;"><div class="card"><img src="/media/photo-200x200.jpg" alt=""><p>Narrow slot</p></div></div>
<div class="slot" style="width: 400px;"><div class="card"><img src="/media/photo-200x200.jpg" alt=""><p>Wide slot</p></div></div>

The same code gave two different layouts — depending on the slot, not the screen.

Why it matters

A media query only knows the window width. But the same card can sit in a wide feed and in a narrow sidebar. A container query lets a component adapt to the space it is given, wherever it is placed.

Container units

Inside a container the cqi unit works — a percentage of its width. For example, font-size: clamp(1rem, 5cqi, 1.5rem) grows with the column.

Common mistake

A @container condition cannot style the container itself — only its descendants. Rules for .slot inside @container will do nothing. That is why you need a separate wrapper element, as in the example.

Functions used in this recipe

  • @container — Applies rules depending on the size of a container rather than the window.
  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • px, em, rem, %, vw, vh — Units for lengths in CSS: absolute pixels and relative units.

Thanks for reading!

Donate to the site — we work hard for you.