Responsive and interactive states

Use container query variants

Adapt a component to the width of its own container with built-in container query utilities and named containers.

8 minute lesson

~~~

Mark a container and respond inside it:

<div class="@container">
  <article class="flex flex-col @md:flex-row">...</article>
</div>

@container establishes an inline-size query container. The @md: variant becomes active when that container—not the viewport—reaches Tailwind’s md container size. Like viewport breakpoints, these variants are mobile-first minimum conditions.

This makes the component portable. At the same browser width, a card can stay stacked in a narrow sidebar and become a row in the main content area.

Nested containers can be named:

<section class="@container/main">
  <article class="grid @md/main:grid-cols-[10rem_1fr]">...</article>
</section>

The name makes the dependency explicit when the nearest unnamed container is not the intended one. Keep names about layout regions rather than one page instance.

Container queries do not replace viewport queries. Page-wide navigation and global gutters often depend on the viewport. A reusable card, toolbar, or widget usually cares about its allocated space. Choose the boundary that owns the constraint.

The parent must actually establish a container. If @md:* never matches, inspect container-type in DevTools and measure the container’s content box. Do not compare the breakpoint against the window width.

Use arbitrary container thresholds only for real exceptions. If several components share a threshold, define a --container-* theme value so the variant has a name and consistent meaning.

Your action is to render the same card in a 20rem sidebar and a flexible main column. Keep the viewport unchanged, inspect both container sizes, and prove that only the wide instance activates @md:.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →