Container queries

Tailwind CSS · Practical · 8 min

Components that respond to their own space can be reused anywhere without page-level breakpoints.

Container queries are built into Tailwind v4. Two steps:

  • Add the @container class to a parent, which sets container-type: inline-size.
  • Use @-prefixed variants on descendants: @md:flex-row applies when the nearest container is at least 28rem wide.

The container sizes are separate from screen breakpoints and smaller: @3xs (16rem), @2xs (18rem), @xs (20rem), @sm (24rem), @md (28rem), @lg (32rem), @xl (36rem), @2xl (42rem) and up to @7xl (80rem). They come from the --container-* theme variables, which also drive max-w-md and friends.

Like screen breakpoints, they're mobile-first, with @max-md: for the opposite direction and ranges such as @sm:@max-md:.

Named containers handle nesting: @container/sidebar on the parent and @lg/sidebar:grid-cols-2 on a child target that container specifically rather than the nearest one.

Arbitrary sizes work too: @min-[400px]:flex.

The cqw and related units are available through arbitrary values, such as text-[5cqw], for type that scales with the container.

Rule of thumb: screen breakpoints (md:) for the page skeleton, container variants (@md:) inside reusable components like cards, list items and widgets.

Example

<!-- The same card adapts to a narrow sidebar or a wide main column -->
<div class="@container">
  <article class="flex flex-col gap-4 rounded-xl bg-white p-4 shadow @md:flex-row">
    <img src="/cover.jpg" alt="Book cover" class="w-full rounded-lg @md:w-40">
    <div>
      <h3 class="text-lg font-semibold @lg:text-xl">Designing Data-Intensive Applications</h3>
      <p class="hidden text-gray-600 @sm:block">A deep dive into storage and streams.</p>
    </div>
  </article>
</div>

<!-- Named container for nested layouts -->
<aside class="@container/sidebar">
  <ul class="grid gap-2 @lg/sidebar:grid-cols-2">...</ul>
</aside>

Remember

  • @container on the parent, @md: etc. on descendants
  • Container sizes are smaller than screen breakpoints (@md = 28rem)
  • Name containers with @container/name for nesting
  • Breakpoints for pages, container variants for components

Watch out for

  • Using @md: without any @container ancestor, so the variant never applies.

Check yourself

  1. Why does @md:flex-row not apply to a card with no @container class above it?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: tailwindcss.com/docs/responsive-design#container-queries

Builds on

Unlocks

Nothing builds on this yet.