Sub topic 1
Why container queries: viewport versus container
Responsive design has long meant one thing: change the layout when the browser window changes size. That works for page-level decisions. It breaks down for reusable components, because a component rarely knows how much room it has. This chapter explains the problem, shows how container queries solve it, and gives you the model you need for the rest of the tutorial.
Prerequisites
This chapter assumes you already know the following:
- Basic HTML and CSS layout, including flexbox and grid.
- Tailwind utility classes such as
flex,gap-4andtext-lg. - Tailwind's responsive variants, such as
md:flex-rowandlg:grid-cols-3. - What a media query is and how viewport-based breakpoints work.
You don't need to know anything about container queries. You also don't need to know whether your project uses Tailwind v3 or v4. Later chapters cover both. The examples here use v4 syntax, where container queries are built in.
The limit of viewport-based responsive design
A media query asks a question about the viewport: "Is the window at least 768px wide?" Tailwind's md: variant is a thin wrapper around that question. In v4, md: compiles to @media (width >= 48rem).
Consider a product card. On a wide screen you want the image beside the text. On a narrow screen you want them stacked. With viewport variants you write this:
<div class="flex flex-col gap-4 md:flex-row">
<img class="w-full md:w-48" src="/photo.jpg" alt="Product photo" />
<div>
<h2 class="text-lg font-semibold">Product name</h2>
<p class="text-sm text-gray-600">Short description of the product.</p>
</div>
</div>This is correct only if the card always spans most of the page. Now place the same card in two spots:
- In a main content area that is 800px wide.
- In a sidebar that is 280px wide.
On a 1400px-wide window, md: is active in both places, because the window is wider than 768px. The card puts the 192px image (w-48) beside the text in a 280px sidebar. That leaves about 70px for the text, so the layout is broken. The card has no way to know it is in a narrow slot. It only knows how wide the window is.
The usual workarounds are all unsatisfying:
- Add a prop or class such as
variant="compact"and set it by hand at every place the card is used. - Write separate sidebar and main-area versions of the component.
- Override styles from the parent with selectors that know about the card's internals.
Each one moves layout knowledge out of the component and into every place that uses it.
The idea behind container queries
A container query asks a different question: "How wide is my parent?" The component responds to the space it was given, not to the window.
The same card now behaves correctly in both slots. In the 800px main area it uses the row layout. In the 280px sidebar it stays stacked. The window width doesn't enter into it. Moving the card to a third location with a different width needs no code changes.
This is the main benefit: a component becomes self-contained. Its layout rules travel with it.
What a container query looks like in Tailwind
Tailwind needs two pieces. First, you mark an ancestor as a container with the @container class. Second, you style descendants with variants prefixed by @, such as @md:.
<div class="@container">
<div class="flex flex-col gap-4 @md:flex-row">
<img class="w-full @md:w-48" src="/photo.jpg" alt="Product photo" />
<div>
<h2 class="text-lg font-semibold">Product name</h2>
<p class="text-sm text-gray-600">Short description of the product.</p>
</div>
</div>
</div>The outer div is the query container. Its child switches from a column to a row once the container is at least @md wide, whatever the viewport width. Compare this with the viewport version above. The only changes are the wrapper and the @ prefix on md:.
Later chapters cover each part in detail: marking containers, the size scale, max and range variants, naming, and more. For now, hold on to this model: a container variant is a condition on the nearest marked ancestor's width.
How it works underneath
Tailwind's @container class is a short way to write native CSS. It generates a rule like this:
.\@container {
container-type: inline-size;
}The @md: variant generates a native container query:
@container (width >= 28rem) {
/* utilities here */
}So you are not using a JavaScript library or a Tailwind-specific trick. The browser evaluates these rules itself, with no script and no resize observers. Container queries are supported in all current major browsers (Chrome, Edge, Safari, Firefox), so you can use them in production for a modern audience.
Two details of container-type: inline-size matter and often surprise people.
- Only the inline axis is queried. In a horizontal writing mode such as English, the inline axis is width. Queries can test the container's width, not its height. Height queries need a different
container-type, and Tailwind's@containerdoesn't set one. - The container can't size itself from its children's width.
inline-sizeestablishes size containment in the inline axis. The browser must compute the container's width without looking at its contents. A container withdisplay: blocknormally fills its parent, so this is fine. A container in a shrink-to-fit context, such as a floated element, an absolutely positioned element or an auto-sized flex or grid item, may collapse to zero width because its content no longer contributes to its width. Give such a container an explicit width, or place it in a context that sizes it.
Another consequence: an element can't query itself. Container variants apply to descendants of the container, never to the container element. If you put @container and @md:flex-row on the same element, the variant does nothing. You need a wrapper.
Viewport variants versus container variants
The two kinds of variant have the same shape but differ in what they measure, and they use different scales.
| Aspect | Viewport variants | Container variants |
|---|---|---|
| Example | `md:flex-row` | `@md:flex-row` |
| Measures | Browser window width | Nearest `@container` ancestor's width |
| Setup needed | None | Mark an ancestor with `@container` |
| Generated CSS | `@media (width >= 48rem)` | `@container (width >= 28rem)` |
| Typical use | Page layout, navigation, global spacing | Reusable components such as cards and widgets |
| Breakpoint for `md` (v4) | 48rem (768px) | 28rem (448px) |
The last row is easy to miss. md: and @md: don't mean the same size. Container sizes are smaller because containers are usually narrower than the window. Chapter 4 covers the full scale. For now, don't assume @md is 768px.
When to use each
Container queries don't replace viewport queries. They answer different questions, and most real projects use both.
Use viewport variants when the decision depends on the device or window:
- Showing a hamburger menu on phones and a full nav bar on desktops.
- Choosing how many columns the page-level grid has.
- Setting page margins and the overall maximum width.
Use container variants when the decision depends on the room a component has:
- A card, media object or profile summary that appears in a sidebar, a modal and a main column.
- A widget in a dashboard whose width depends on the user's layout.
- A component library item whose host page you don't control.
A useful rule: the page decides how much space each region gets, using viewport queries. Each component then decides how to use the space it received, using container queries. In practice, a viewport variant often changes a region's width, and a container variant inside responds to the result.
Here is that division in one example. The page layout uses a viewport variant. The card uses a container variant.
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_20rem]">
<main class="@container">
<article class="flex flex-col gap-4 @md:flex-row">
<img class="w-full @md:w-48" src="/photo.jpg" alt="Product photo" />
<div>
<h2 class="text-lg font-semibold">Product name</h2>
<p class="text-sm text-gray-600">Short description of the product.</p>
</div>
</article>
</main>
<aside class="@container">
<article class="flex flex-col gap-4 @md:flex-row">
<img class="w-full @md:w-48" src="/photo.jpg" alt="Product photo" />
<div>
<h2 class="text-lg font-semibold">Product name</h2>
<p class="text-sm text-gray-600">Short description of the product.</p>
</div>
</article>
</aside>
</div>Below the lg viewport breakpoint, both regions are full width, so both cards go to the row layout if the screen is wide enough for @md. At lg and above, the aside is fixed at 20rem (320px), which is wider than @md at 28rem? No: 20rem is narrower than 28rem, so the aside card stays stacked, while the main card gets the remaining space and switches to a row. You didn't write any rule that mentions the sidebar inside the card.
Common misunderstandings
- "Container queries make
md:obsolete." They don't. Page-level decisions still belong to the viewport. - "
@mdis the same asmd." The names match, but the sizes don't. - "Any parent works as a container." Only an ancestor with
@container(or equivalentcontainer-type) counts. Without one,@md:variants are ignored, because no container is available to query. This is the most common problem and gets full coverage in the final chapter. - "A container can respond to its own size." It can't. Only its descendants can.
Check your understanding
Exercise
A card uses flex-col md:flex-row. It is placed in a 300px sidebar on a 1600px-wide window, and the layout is cramped. Explain why md: fails here, and describe the two changes that fix it with container queries.
Show answer
md: compiles to a media query on the viewport, and a 1600px window is wider than the md breakpoint, so the row layout applies no matter how narrow the sidebar is. The fix has two parts. First, add the @container class to an ancestor of the card, such as the sidebar wrapper, so the card has a container to measure. Second, change md:flex-row to @md:flex-row. The row layout then applies only when the container is at least 28rem wide, so the card in a 300px sidebar stays stacked.
Exercise
You write <div class="@container @md:flex-row flex-col"> and the layout never changes when you resize the container. What is wrong?
Show answer
A container query variant applies only to descendants of the container, never to the container itself. The element can't query its own width. Move @container to a wrapper element and put flex flex-col @md:flex-row on a child inside it.