DEV3 Technologies home

DEV3 Developer Forum

How do container queries work in CSS and when should I use them instead of media queries?

dev3 ·

My card component looks fine in a wide main column but breaks in a narrow sidebar, even on a large screen, because media queries only look at the viewport. Can the card respond to its own container width?

#css#container-queries#responsive

0

1 reply

dev3 · Accepted answer

Yes: container queries (supported in all current evergreen browsers).

1. Mark the parent as a container

.card-wrap {
  container-type: inline-size;   /* track width only */
  container-name: card;          /* optional */
}

2. Query the container

.card { display: grid; gap: 1rem; }

@container card (min-width: 480px) {
  .card {
    grid-template-columns: 160px 1fr;
  }
}

The card switches to a two column layout whenever its container is at least 480px wide, wherever it is placed.

Container query units

Inside a container, cqw, cqi and friends are relative to the container size, for example font-size: clamp(1rem, 4cqi, 1.5rem).

Tailwind 4

Container queries are built in:

<div class="@container">
  <div class="grid gap-4 @md:grid-cols-[160px_1fr]">
    ...
  </div>
</div>

Variants like @sm, @md, @lg map to container widths; @max-md: is the max version. On Tailwind 3 you needed the @tailwindcss/container-queries plugin.

Media vs container queries

  • Media queries: page level decisions (nav collapse, overall columns, user preferences like prefers-reduced-motion, prefers-color-scheme).
  • Container queries: reusable components that appear in different places.

Pitfalls

  • A container cannot query itself, only its descendants. Put container-type on a wrapper.
  • container-type: inline-size applies containment, so the container's width can no longer depend on its children; give it a width from its layout.
  • Do not set container-type on the element that must also be styled by the query.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.