Container queries

Components that respond to their own width, not the screen's.

What it is

Media queries (md:, lg:) ask how wide the screen is. A component doesn't know where it will be placed, so the screen is the wrong question: the same card might sit in a narrow sidebar on a wide monitor. A container query asks how wide the container is instead. In Tailwind v4 it's built in: mark an element @container, and its descendants can use @sm:, @lg: and the rest, or @max-sm: for below a size. The sizes come from the --container-* tokens (@sm is 24rem).

When to use it

  • Reusable components: cards, media objects, forms that sit in columns of any width
  • Keep media queries for the page's own layout (sidebar, columns)
  • Name a container (@container/panel) when nested containers would answer the wrong question
Official docs ↗

1. A card that reads its own width

  • @max-sm <24rem
  • @xs 20rem
  • @sm 24rem
  • @md 28rem
  • @lg 32rem
  • @xl 36rem
  • @2xl 42rem

Sam Rivera

Front-end developer

Drag the slider: the badges light up through the variants they name, and the card stacks, goes into a row at @sm, then shows its stats at @lg. The window never changed size.

2. Same component, different places

Narrow sidebar

Sam Rivera

Front-end developer

Main column

Sam Rivera

Front-end developer

Both cards are the same markup at the same screen width, and each picks the layout that fits its slot. With sm: media queries they'd both switch together.

3. Named containers

Outer container, named panel

Inner container, half as wide

@sm: nearest ≥ 24rem

@sm/panel: panel ≥ 24rem

The inner box is a container too, so a plain @sm: measures it, the nearest one. Naming the outer one @container/panel lets @sm/panel: skip past it. From about 48rem the outer panel matches while the inner box still doesn't.

Show code · src/app/tailwind/container-queries/ProfileCard.tsx
// One component, three layouts, chosen by the width it's given rather than the
// screen's: stacked when narrow, a row from @sm (24rem), and with stats from
// @lg (32rem). The outer div is the container the variants measure.
export function ProfileCard() {
  return (
    <div className="@container">
      <div className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4 @sm:flex-row @sm:items-center @lg:gap-5">
        <span aria-hidden="true" className="grid size-12 shrink-0 place-items-center rounded-full bg-accent font-bold text-white @lg:size-14">
          SR
        </span>
        <div className="min-w-0 @sm:flex-1">
          <p className="m-0 font-semibold">Sam Rivera</p>
          <p className="m-0 text-sm text-muted">Front-end developer</p>
        </div>
        <dl className="m-0 hidden gap-4 text-center @lg:flex" data-testid="profile-stats">
          <div><dt className="text-xs text-muted">Posts</dt><dd className="m-0 font-semibold tabular-nums">128</dd></div>
          <div><dt className="text-xs text-muted">Followers</dt><dd className="m-0 font-semibold tabular-nums">2.4k</dd></div>
        </dl>
        <button type="button" className="rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-white @max-sm:w-full">
          Follow
        </button>
      </div>
    </div>
  );
}
Show code · src/app/tailwind/container-queries/Demos.tsx
"use client";

import { Resizer } from "@/components/Resizer";
import { Breakpoints } from "./Breakpoints";
import { ProfileCard } from "./ProfileCard";

export function ResizableCard() {
  return (
    <Resizer testId="card-box">
      <div className="grid gap-3">
        <Breakpoints />
        <ProfileCard />
      </div>
    </Resizer>
  );
}

// Containers nest, and a plain @sm: asks the nearest one. Name a container
// (@container/panel) to ask a particular ancestor instead: @sm/panel:.
const badge = "m-0 rounded-md bg-code px-2 py-1 font-mono text-xs text-muted";

export function NamedContainers() {
  return (
    <Resizer testId="panel-box" initial={44} max={60}>
      <div className="@container/panel rounded-xl border border-line p-3">
        <p className="m-0 mb-2 text-xs text-muted">Outer container, named <code>panel</code></p>
        <div className="@container w-1/2 rounded-lg border border-dashed border-line bg-bg p-2">
          <p className="m-0 mb-2 text-xs text-muted">Inner container, half as wide</p>
          <div className="grid gap-1.5">
            <p className={`${badge} @sm:bg-accent @sm:text-white`} data-testid="nearest">@sm: nearest ≥ 24rem</p>
            <p className={`${badge} @sm/panel:bg-accent @sm/panel:text-white`} data-testid="named">@sm/panel: panel ≥ 24rem</p>
          </div>
        </div>
      </div>
    </Resizer>
  );
}
Show code · src/components/Resizer.tsx
"use client";

import { type ReactNode, useEffect, useRef, useState } from "react";

// A box with a width slider, so a demo can show what happens at any width
// without resizing the window. The box is a container (@container), and the
// readout is its measured width: what container queries and cqi units see.
// It never gets wider than the page, so on a phone the top of the range is
// the screen's width.
export function Resizer({
  children,
  label = "Container width",
  min = 14,
  max = 56,
  initial = 36,
  onResize,
  testId,
}: {
  children: ReactNode;
  label?: string;
  min?: number;
  max?: number;
  initial?: number;
  onResize?: (width: number) => void;
  testId?: string;
}) {
  const [rem, setRem] = useState(initial);
  const [px, setPx] = useState<number | null>(null);
  const box = useRef<HTMLDivElement>(null);
  const report = useRef(onResize);
  useEffect(() => {
    report.current = onResize;
  });

  useEffect(() => {
    const observer = new ResizeObserver(([entry]) => {
      const width = Math.round(entry.contentBoxSize[0].inlineSize);
      setPx(width);
      report.current?.(width);
    });
    observer.observe(box.current!);
    return () => observer.disconnect();
  }, []);

  return (
    <div className="grid grid-cols-[minmax(0,1fr)] gap-3">
      <label className="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)_4.5rem] items-center gap-3 text-sm">
        <span>{label}</span>
        <input type="range" min={min} max={max} step={0.5} value={rem} onChange={(e) => setRem(Number(e.target.value))} className="w-full" />
        <output className="text-right font-mono text-xs tabular-nums" data-testid={testId && `${testId}-width`}>
          {px === null ? "…" : `${px}px`}
        </output>
      </label>
      <div ref={box} style={{ width: `min(100%, ${rem}rem)` }} className="@container" data-testid={testId}>
        {children}
      </div>
    </div>
  );
}