Sub topic 2
The Default Container Size Scale
Assume you know basic flexbox and grid, Tailwind utility classes, and viewport variants such as md:. Container queries use the nearest marked container, not the browser viewport.
The default container size scale
Add @container to an ancestor. A child can then use @sm, @md, or another container variant. Tailwind compares the ancestor's inline size with its container scale.
| Variant | Minimum container width |
|---|---|
| `@sm` | 24rem |
| `@md` | 28rem |
| `@lg` | 32rem |
| `@xl` | 36rem |
| `@2xl` | 42rem |
For example, @md:grid-cols-2 applies when the query container is at least 28rem wide. These thresholds are independent of the viewport width.
<div class="@container">
<div class="grid grid-cols-1 gap-4 @md:grid-cols-2 @lg:grid-cols-3">
<article class="rounded-lg border p-4">Card one</article>
<article class="rounded-lg border p-4">Card two</article>
<article class="rounded-lg border p-4">Card three</article>
</div>
</div>Max and range variants
Use @max-md: for sizes below the md threshold. Combine variants to target a range:
<div class="@container">
<div class="flex flex-col @md:@max-xl:flex-row">
<div>Thumbnail</div>
<div>Details</div>
</div>
</div>Here, the row layout applies from @md through below @xl. At smaller sizes, the content remains stacked. A range is useful when a component needs a compact layout at both very small and very large sizes, but a different layout in the middle.
Building a reusable card
A reusable component should respond to its own available space. The same markup can appear in a sidebar, a modal, or a full-width page section.
<article class="@container rounded-lg border p-4">
<div class="flex flex-col gap-4 @md:flex-row">
<img class="h-40 w-full object-cover @md:h-24 @md:w-24"
src="/product.jpg" alt="Blue travel backpack" />
<div>
<h2 class="font-semibold">Travel backpack</h2>
<p class="text-sm text-gray-600">Lightweight and water resistant.</p>
</div>
</div>
</article>The @container class belongs on the card. The @md: variants belong on descendants that change when the card becomes wide enough.
Exercise
Why can this card adapt correctly inside both a narrow sidebar and a wide page section?
Show answer
Its variants measure the card's marked container, so they respond to the card's available width rather than the viewport.