पाठ 19 / 25

Container Queries

Respond to the parent, not the viewport.

@container and @md:

A component placed in a narrow sidebar and a wide main area should adapt to its container, not the screen. Mark the parent with @container, then use container variants on children: @md:flex-row applies when the container is at least the md container size. Named containers (@container/card with @md/card:) target a specific ancestor. Container queries are built into Tailwind v4 without a plugin.

Beyond the basics

Container queries, transitions and accessibility utilities make components robust and inclusive.

Three ideas: container queries, transitions and animation, accessibility.
Figure 7.1 — Container queries, motion and accessibility.

A card that adapts to its container

Stacked in narrow spaces, side by side in wide ones.

<div class="@container">
  <article class="flex flex-col gap-4 rounded-xl border p-4 @md:flex-row">
    <img class="w-full rounded-lg @md:w-40" src="/thumb.jpg" alt="">
    <div>
      <h3 class="font-semibold">Container queries</h3>
      <p class="text-sm text-gray-600">This card responds to the width of its parent.</p>
    </div>
  </article>
</div>

Use viewport breakpoints for pages, containers for components

Page layout depends on the screen; reusable components depend on where they are placed.

त्वरित जाँच: What must you add before @md: variants work?

  • A JavaScript resize listener
  • A media query in CSS
  • The md: variant on the same element
  • The @container class on an ancestor
Answer

The @container class on an ancestor — Mark the container first.