Tailwind CSS Tutorial · Layout · Lesson 14 of 27
Container Queries
Making components respond to the size of their container instead of the screen, with @container and @sm:, @md: variants.
Why container queries?
Breakpoints look at the screen. But a card in a narrow sidebar and the same card in a wide main column need different layouts on the same screen. Container queries solve this:
- Mark the parent with
@container. - Use
@sm:,@md:,@lg:… on children; they respond to the container's width.
Container sizes: @3xs (16rem), @2xs (18rem), @xs (20rem), @sm (24rem), @md (28rem), @lg (32rem),
@xl (36rem), @2xl (42rem) and larger. They're built into Tailwind v4, no plugin needed.
<div class="grid gap-4 p-4 sm:grid-cols-[14rem_1fr]">
<div class="@container rounded-lg bg-gray-100 p-2">
<div class="flex flex-col gap-3 rounded-lg bg-white p-3 @sm:flex-row">
<div class="h-20 shrink-0 rounded bg-sky-400 @sm:w-24"></div>
<p class="text-sm">Narrow container: stacked</p>
</div>
</div>
<div class="@container rounded-lg bg-gray-100 p-2">
<div class="flex flex-col gap-3 rounded-lg bg-white p-3 @sm:flex-row">
<div class="h-20 shrink-0 rounded bg-sky-400 @sm:w-24"></div>
<p class="text-sm">Same card, wide container: side by side</p>
</div>
</div>
</div>
Name containers when they're nested: @container/sidebar and @md/sidebar:flex.
Test yourself
What must you add to a parent before using @md: on its children?
@containercontainerrelativemd:container
Show answer
Answer: @container
@container makes the element a query container.