Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readCSS

Use built-in container queries in Tailwind v4

Use named Tailwind container variants to change an event card’s layout and spacing by the width of its slot.

You use the same event card in a sidebar and in the main column. On a wide screen, a viewport breakpoint puts both cards in a row, even when the sidebar has no room. Tie the card's layout to the width of its slot.

Name the container around the card

Tailwind v4 includes container query variants. Add @container/card to the wrapper and put the variants on its descendant. The name card lets the variants find the nearest eligible ancestor named card, even through an intervening container with another name.

In a Tailwind v4 stylesheet with @import "tailwindcss", use this HTML. The wrapper takes its width from the parent slot.

<div class="@container/card">
  <article class="flex flex-col gap-3 @sm/card:flex-row @lg/card:gap-6">
    <div class="shrink-0">Sat, 18 July</div>
    <div>
      <h2>Trail cleanup</h2>
      <p>Meet at the north gate.</p>
    </div>
  </article>
</div>

The event details stack in a narrow slot, then sit beside the date once the slot reaches 24rem.

An ordinary sm: variant checks the viewport. The @sm/card: variant checks the named container and has its own scale. With the defaults, @sm starts at 24rem and @lg starts at 32rem. The gap grows at 32rem while the row layout continues to apply.

diagram

The same card in three slots

The date and details share a row at 24rem, and their gap grows at 32rem.

Test the two slots on one screen

Put a copy in a 20rem parent and another in a 34rem parent. Keep the browser window the same width. If you see one column and one row, you have a card that responds to its slot even when both copies share a viewport.

If both copies stay stacked, inspect the wrapper for container-type: inline-size and container-name: card. Then check that the variant sits below that wrapper. Putting the container and its own query variant on the same element leaves the variant looking for a matching ancestor.

Compare the generated rules with the plain CSS version to see how the named container supplies the breakpoint.