Sub topic 2
Marking a container with @container
This chapter covers the @container class: what CSS it generates, what it changes about the element that carries it, and how child variants find it. It assumes you know flexbox and grid, can read Tailwind utility classes, use variants such as md: and lg:, and know that a media query tests the viewport. The previous chapter covered why container queries exist. This one covers how to switch them on.
What the class generates
A container query needs two parts: an element that declares itself a query container, and descendants with styles that depend on that element's size. In plain CSS, the declaration is the container-type property:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 28rem) {
.card {
flex-direction: row;
}
}Tailwind's @container class produces the first part. It sets container-type: inline-size on the element. The @md:, @lg: and similar variants produce the second part, the @container (min-width: ...) rule. Nothing in the markup connects the two. The browser matches them by walking up the tree from each styled element to its nearest ancestor that is a query container.
The class name starts with @, which has no special meaning in HTML. It is a naming convention that matches the @ in the variants, so a container and its variants read as a pair.
A minimal working example
<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 (28rem in the default scale). The viewport width does not matter. Put this markup in a 20rem sidebar on a 2000px monitor and it stays stacked. Put it in a 40rem main column on a narrow window and it goes horizontal.
The @md: variant on the inner element is not a media query. It compiles to a rule scoped to the width of the nearest container ancestor.
How a variant finds its container
The lookup follows three rules:
- The browser starts at the element's parent and moves upward.
- It stops at the first ancestor with a
container-typethat allows width queries. - It evaluates the condition against that ancestor's content box width.
If no ancestor qualifies, the condition cannot match and the style is not applied. The browser does not fall back to the viewport, and it does not log an error.
Two consequences follow from this lookup.
- The container cannot style itself. An element with
@container @md:p-8does not get the padding from its own width. The variant looks at ancestors only. Style the container's children, or add another wrapper. - Only the nearest container counts. Marking a distant ancestor does nothing if a closer one exists. Chapter 7 covers named containers, which override this.
What `container-type: inline-size` does to the element
Marking an element as a container is not free. The browser applies containment to it. For inline-size, three things happen, and each can change how the page looks.
Inline size containment
The container's width can no longer depend on its contents. The browser treats its content as having zero width when calculating the container's own size. This is necessary: if the width depended on the children and the children depended on the width, the layout would loop.
A block-level div in normal flow takes its width from its parent, not from its contents, so it is unaffected. Problems appear where the width normally comes from the contents:
| Context | Normal behavior | With `@container` |
|---|---|---|
| `display: inline-block` | Shrinks to fit content | Collapses to zero width |
| Flex item with `auto` basis | Sized by content | Can collapse to zero width |
| Grid column sized `auto` | Sized by content | Can collapse |
| Floated element with no width | Shrinks to fit content | Collapses |
| Absolutely positioned, `width: auto` | Shrinks to fit content | Collapses |
In each case, give the container an explicit width source. Use w-full, w-64, flex-1, a fixed grid track, or grid-cols-[1fr_2fr].
Only the inline axis is contained. The height still comes from the contents as usual, which is why inline-size is the default and not full size containment.
Layout and style containment
The container also gets layout containment and style containment. In practice this means:
- It becomes the containing block for absolutely and fixed-positioned descendants. A
fixedchild will position against the container, not the viewport. - It creates a new stacking context, so
z-indexvalues inside it no longer compete with elements outside it. - It becomes an independent formatting context, so margins of children do not collapse through it.
Most pages never notice these. A modal or dropdown inside a container with fixed inset-0 is the usual exception. See the pitfalls section below.
Where to put the class
Put @container on the element whose width you want to measure, and make sure its children carry the variants. Three placements are common.
- On a wrapper inside the component. The component brings its own container, so it adapts anywhere. This is the most portable choice.
- On a layout region such as a sidebar, a main column, or a dashboard panel. Every component inside responds to that region.
- On a grid or list item. Each item measures itself, so cards in the same row can differ if their tracks have different widths.
The next example uses the third placement. One grid item gets its own container, and the card inside reacts to that item's width:
<ul class="grid grid-cols-[2fr_1fr] gap-6">
<li class="@container">
<article class="flex flex-col gap-3 rounded border p-4 @sm:flex-row @sm:items-center">
<h3 class="font-semibold">Wide slot</h3>
<p class="text-sm text-gray-600">Lays out as a row when this slot is at least 24rem wide.</p>
</article>
</li>
<li class="@container">
<article class="flex flex-col gap-3 rounded border p-4 @sm:flex-row @sm:items-center">
<h3 class="font-semibold">Narrow slot</h3>
<p class="text-sm text-gray-600">The same markup, stacked because this slot is narrower.</p>
</article>
</li>
</ul>The two article elements have identical classes. The grid gives them different widths, and each picks its own layout. A viewport breakpoint could not do this, because both articles see the same viewport.
Content box, padding and borders
A container query measures the container's content box. Padding and borders on the container are excluded. If you write @container p-8 and the element is 32rem wide, children see a container of 32rem minus 4rem of padding, which is 28rem. That is exactly the @md threshold, and any rounding or scrollbar will push it below.
When a breakpoint seems to trigger at a different size than expected, check for padding on the container element. A clean fix is to keep the container unpadded and put the padding on an inner element:
<div class="@container">
<div class="p-8">
<div class="grid grid-cols-1 gap-4 @lg:grid-cols-2">
<div>First</div>
<div>Second</div>
</div>
</div>
</div>Here the queried width is the full outer width, and the padding still applies to the content.
Resetting a container
Tailwind v4 provides @container-normal, which sets container-type back to normal. Use it to cancel the class at a state or breakpoint, for example when a component should only act as a container in some layouts. For a variant-controlled reset, lg:@container-normal removes containment above a viewport size. Most projects never need it.
Containers and Tailwind versions
In Tailwind v4, @container and the @sm, @md style variants are part of core. Nothing needs installing.
In v3 they come from an official plugin and the class does nothing without it:
// tailwind.config.js (Tailwind v3 only)
module.exports = {
theme: {
extend: {},
},
plugins: [require('@tailwindcss/container-queries')],
}A common mistake is copying v4 markup into a v3 project. The @container class generates no CSS, the variants do not exist, and the page shows the unstyled base layout. Chapter 11 covers the v3 setup.
Common pitfalls and how to debug them
The variant never applies
This is the most common failure. Check, in order:
- Is there an
@containerancestor at all? Search the parent chain in the browser's element inspector. Look forcontainer-type: inline-sizein the computed styles. - Is the container too narrow? Compare its content width to the variant's threshold. A 27rem container does not match
@md. - Is the variant on the container itself? Move it to a child.
- Is the container the nearest one? An unexpected closer container, perhaps from a UI library, changes which width is measured.
- Is the Tailwind version right? On v3 the plugin must be installed.
Browser developer tools help here. Chrome and Firefox mark elements that are query containers in the Elements panel, and the Styles panel shows the @container rule with its matching state.
The container has zero width
If the container is inline-level, floated, a content-sized flex or grid item, or absolutely positioned without a width, it collapses, and every variant measures a tiny container. Symptom: the @container element is invisible or the children are squeezed to a sliver. Add w-full or another explicit width source.
A fixed or absolute child jumps
A fixed inset-0 overlay inside a container is positioned against the container because of layout containment, not against the viewport. Move overlays outside the container, or render them through a portal at the document root.
A stacking order changes
The container makes a new stacking context. A dropdown inside it can no longer rise above content outside it, whatever its z-index. Raise the z-index on the container itself, or move the dropdown.
Summary
@containersetscontainer-type: inline-sizeon an element, making it a target for@sm,@md,@lgand related variants on its descendants.- A variant measures the nearest ancestor container's content width. With no container ancestor, the style does not apply, silently.
- The container cannot respond to its own width. Variants belong on children.
- Inline size containment means the container's width must come from outside. Give flex, grid, inline and floated containers an explicit width.
- Containment also creates a stacking context and a containing block for fixed and absolute descendants.
- Padding on the container reduces the measured width. Prefer an inner padded wrapper.
- Tailwind v4 has the feature in core. Tailwind v3 needs
@tailwindcss/container-queries.
Exercise
A developer writes <div class="@container @lg:grid-cols-2 grid grid-cols-1">...</div> and sees the grid stay at one column even in a very wide container. Why, and how do they fix it?
Show answer
The @lg: variant is on the container element itself, and container variants only look at ancestors, so no container is found for it. Fix it by wrapping: <div class="@container"><div class="grid grid-cols-1 @lg:grid-cols-2">...</div></div>.
Exercise
A badge is placed in a flex row as <span class="@container inline-block">. Its children's @sm: styles never apply, and the badge is invisible. What causes this, and what is one change that fixes it?
Show answer
container-type: inline-size applies inline size containment, so the badge's width can no longer come from its content. As an inline-block it collapses to zero width, and the queried width is far below @sm. Give it a width source, for example w-48 or flex-1 (and use block or a flex item instead of inline-block).
Exercise
A container is 32rem wide and has p-6 (1.5rem on each side). Does a child with @lg: (32rem) match, and why?
Show answer
No. The query measures the content box, which is 32rem minus 3rem of horizontal padding, or 29rem. That is below the 32rem @lg threshold. Moving the padding to an inner wrapper makes the container's measured width 32rem.