日本語

How to Use CSS Container Queries in React to Change Layout by Placement

​​React​Container Queries,CSS,Playwright,TypeScript

This article was translated from the Japanese original with AI. 日本語の原文を読む

With CSS container queries, you can change the shape of a React component based on the width of the place it is put in, not the width of the screen. The same product card can be laid out side by side in a wide column and stacked vertically in a narrow spot. This is useful on responsive pages where the same part is placed in containers of different widths. No JavaScript is needed to measure the width. Add container-type to the slot element, and write the conditions in the card's CSS with @container.

Note

The test environment was Ubuntu 24.04 and Node.js 22.22.0. I used react / react-dom 19.3.1, @types/react 19.3.0 (type definitions from csstype 3.2.3), typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, converted them for development with esbuild, drove Chrome for Testing 153 (Chromium) with Playwright 1.64.1, and read the computed styles. I did not test Firefox, Safari, or real smartphones.

The slot element and the card's CSS

First, I create CardSlot, the component that is the place where the card is put, and ProductCard, the card itself. On the React side, it only needs a class name.

tsx
import type { ReactNode } from 'react';
import './ProductCard.css';

type ProductCardProps = {
  name: string;
  price: number;
  description: string;
};

export function ProductCard({ name, price, description }: ProductCardProps) {
  return (
    <article className="product-card">
      <div className="product-card__image" />
      <div>
        <h3 className="product-card__title">{name}</h3>
        <p className="product-card__price">{price.toLocaleString('ja-JP')}円</p>
        <p className="product-card__desc">{description}</p>
      </div>
    </article>
  );
}

// The slot where the card is placed. The width of this element decides the card's shape
export function CardSlot({ children }: { children: ReactNode }) {
  return <div className="card-slot">{children}</div>;
}

In the CSS, I give .card-slot container-type: inline-size so that it becomes the container whose width the @container conditions check. I also give it a name with container-name. The card's base styles are written for the narrow case, and the wide layout goes inside @container card-slot (width >= 400px).

css
/* The slot element. The @container conditions check the width of this element */
.card-slot {
  container-type: inline-size;
  container-name: card-slot;
}

/* Narrow layout (base) */
.product-card {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  padding: 16px;
  border: 2px solid #00c8e8;
  border-radius: 10px;
  background: #eefafd;
  color: #1f2a30;
}
.product-card__image {
  aspect-ratio: 16 / 9;
  border-radius: 8px;
  background: #00c8e8;
}
.product-card__title {
  margin: 0;
  font-size: clamp(16px, 5cqi, 26px);
}
.product-card__desc {
  display: none;
  margin: 0;
}

/* Layout when the width of the slot is 400px or more */
@container card-slot (width >= 400px) {
  .product-card {
    grid-template-columns: 140px 1fr;
    align-items: center;
  }
  .product-card__desc {
    display: block;
  }
}

According to MDN's guide to container queries, inline-size is a value that judges the condition by the size in the container's inline direction (horizontal for horizontal writing). The 5cqi unit in the title means 5% of the container's size in the inline direction.

On the usage side, you just wrap the card in CardSlot. The card does not receive as props where it is placed. Here are the two placement parts taken from the test page.

tsx
<div style={{ width: 560 }}>
  <CardSlot><ProductCard {...item} /></CardSlot>
</div>
<div style={{ width: 260 }}>
  <CardSlot><ProductCard {...item} /></CardSlot>
</div>
In the 560px-wide slot, a side-by-side card with the image on the left and the name, price, and description on the right. In the 260px-wide slot, a stacked card with the image on top and only the name and price below
The same ProductCard placed in slots 560px and 260px wide

The window width stayed at 900px. These are the computed styles read from the two slots.

text
幅 560px の場所: {"slotWidth":560,"columns":"140px 372px","desc":"block","descInDom":1,"titleFont":"26px"}
幅 260px の場所: {"slotWidth":260,"columns":"224px","desc":"none","descInDom":1,"titleFont":"16px"}

In the 560px slot, the grid had two columns and the description was shown. In the 260px slot, the grid had one column and the description was hidden. The heading size fits within the limits: in the 560px slot, 5% is 28px, which is capped at 26px; in the 260px slot, 5% is 13px, which is raised to the 16px minimum.

Before and after the threshold, and when the width changes

I put the slot width in state and compared 400px with 399px.

text
置き場所の幅 400px: {"slotWidth":400,"columns":"140px 212px","desc":"block","descInDom":1,"titleFont":"20px"}
置き場所の幅 399px: {"slotWidth":399,"columns":"363px","desc":"none","descInDom":1,"titleFont":"19.95px"}

I wrote width >= 400px, so the side-by-side layout applied at exactly 400px. When the width changes, the browser evaluates the condition again. MDN's @container page also says the condition is evaluated when the container's size changes. ProductCard still does not receive any props about the width change.

Dragging the slider to change the slot width from 560px to 420px, then 300px, then back to 560px. The card switches from side-by-side to stacked, then back to side-by-side. At the moment of each switch, the card border and layout display turn pink
Changing the slot width with a slider switches the card’s layout

A styled @container rule does not apply to the container element itself

Even if I apply styles inside @container to the element that has container-type, they do not take effect on that element. I took a 560px-wide element with container-type: inline-size, and inside @container (width >= 400px) I made its background and its child's text color pink.

text
{"width":560,"selfBackground":"rgb(255, 255, 255)","childColor":"rgb(216, 88, 120)"}

The child text turned pink, but the element's own background stayed white. MDN's @container page also states that when the condition matches, the styles apply to descendants of the container. Because I wanted the card's whole frame, including its border, to change shape, this article uses a separate outer element, CardSlot, for the container.

Placed in a flex row, the width becomes 0

I put CardSlot in a display: flex row 600px wide, next to a 100px element. CardSlot had no width or flex set. Only in the second row did I add flex: 1 to CardSlot.

text
row-plain: {"slotWidth":0,"columns":"42.9688px","desc":"none","descInDom":1,"titleFont":"16px"}
row-grow: {"slotWidth":492,"columns":"140px 304px","desc":"block","descInDom":1,"titleFont":"24.6px"}

In the row with no width set, the slot's width became 0, and the card stayed stacked. The grid column width (42.9688px) overflowed the 0-width slot. In the row with flex: 1, the slot grew into the remaining 492px and the layout became side by side.

Note

An element with container-type: inline-size no longer takes its inline size from its content. MDN's container-type page says the container's size must come either from the outside, like a block element that fills its parent, or from an explicit value. Without either, it collapses. When the placement does not set the width from outside, such as when it is a flex child, give it a width or a flex: 1 or similar.

The same page gives the reason. If the size came from the content, the styles applied by a query could change the content's size, which could change the query result again, and this could repeat.

When nested, name the container used for the check

A @container (width >= 400px) without a name checks against the nearest ancestor container. I put a 250px-wide inner container inside a 600px outer container named page, and compared the text color inside.

text
{"outer":600,"inner":250,"nearest":"rgb(0, 0, 0)","named":"rgb(216, 88, 120)"}

The unnamed condition was checked against the nearer 250px container, did not match, and the text stayed black. The condition named @container page (width >= 400px) was checked against the outer 600px container, and the text turned pink. This matches the description on MDN's @container page. A card may contain other parts that have their own containers, so the card's CSS adds the card-slot name to its condition to choose which container is checked.

When writing style attributes, watch for wrong values

container-type and container-name can also be written in React's style attribute. However, as MDN's style attribute page explains, the style attribute takes CSS declarations. @container conditions must be written in a CSS file.

tsx
<div style={{ width: 560, containerType: 'inline-size', containerName: 'card-slot' }}>
  <ProductCard {...item} />
</div>
<div style={{ width: 560, containerType: 'inline', containerName: 'card-slot' }}>
  <ProductCard {...item} />
</div>

The second one has a typo: inline instead of inline-size. However, tsc type checking passed. This is because the csstype types used by @types/react accept arbitrary strings for containerType in addition to the listed values.

ts
export type ContainerType = Globals | "inline-size" | "normal" | "scroll-state" | "size" | (string & {});

When I opened the page in the browser, the results were as follows.

text
ok: {"styleAttr":"width: 560px; container: card-slot / inline-size;","containerType":"inline-size","columns":"140px 372px"}
typo: {"styleAttr":"width: 560px; container-name: card-slot;","containerType":"normal","columns":"524px"}

The correctly written one showed a side-by-side layout. In the typo one, container-type did not remain in the style attribute, and the value stayed at the default normal. Since the element did not become a container, the card stayed stacked even though it was 560px wide. No error appeared on the page. If you build a placement component, it is safer to apply the value through a CSS class, as CardSlot does, so that typos are less likely.

React still renders hidden elements

Even in the card in the 260px slot, the description p element was in the DOM (descInDom was 1). Container queries change only the CSS. Even when an element is hidden with display: none, React still creates it. If the hidden part involves heavy processing, or if you want to change the component itself, use a JavaScript approach that receives the slot width, such as ResizeObserver.

Point

Add container-type: inline-size to the outer element that serves as the placement, and write conditions in the component's CSS in the form @container name (width >= 400px). Make the outer element one whose width is set from its parent. The React component does not need to receive the placement as props; its shape changes based on the width of the place where it is put.

​Posted by 86