CSS Container Queries (@container)

CSS Container Queries (@container) in CSS: Traditional media queries check the dimensions of the browser viewport.

Traditional media queries check the dimensions of the browser viewport. In modern component-driven architectures (React, Vue, Web Components), a component might be placed in a full-width hero section, a narrow 250px sidebar, or a modal window.

Container Queries allow a component to query and style itself based on the width of its parent container, enabling truly modular, portable UI components.


Step 1: Establishing a Container Context

To query an element's parent, declare container-type on the parent wrapper:

.card-wrapper {
  /* Tracks the inline (width) dimension of this container */
  container-type: inline-size;
  container-name: cardContainer; /* Optional named container */
}
  • inline-size: Queries the container's width.
  • normal: Default; not a query container.
  • size: Queries both width and height (requires explicit height on container).

Step 2: Querying the Container with @container

/* Base Mobile/Narrow Layout (Default) */
.product-card {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.product-image {
  width: 100%;
  aspect-ratio: 16 / 9;
}

/* When the parent container is at least 450px wide:
   Switch to a horizontal layout regardless of screen size! */
@container cardContainer (min-width: 450px) {
  .product-card {
    flex-direction: row;
    align-items: center;
  }
  
  .product-image {
    width: 35%;
    aspect-ratio: 1 / 1;
  }
  
  .product-details {
    width: 65%;
  }
}

Container Query Units (cqw, cqh)

Similar to viewport units (vw, vh), modern CSS introduces container query units:

  • 1cqw: 1% of the query container's inline width.
  • 1cqh: 1% of the query container's block height.
/* Typography that scales relative to the parent card's width! */
.card-title {
  font-size: clamp(1.2rem, 5cqw, 2rem);
}

Exercises

  1. Build a weather widget component that renders a compact vertical card when placed in a sidebar, but expands into a detailed horizontal dashboard when placed in the main content area.
  2. Explain the difference between vw viewport units and cqw container query units.
  3. Why does setting container-type: inline-size prevent layout recursion infinite loops in browser rendering engines?