Container Queries

A Component Responds to Its OWN Size

Container Queries

Container queries (`@container`) let a component change layout based on its container's size — not the viewport.

4 min read Level 2/5 #css#container-queries#responsive
What you'll learn
  • Set up a containment context
  • Use `@container` rules
  • Pick container queries vs media queries

Media queries respond to the viewport. Container queries respond to a container’s size — so the same component can look different when it’s wide vs narrow, regardless of the overall screen.

A Concrete Example

A card might lay out vertically when it’s narrow, horizontally when wide. Without container queries you’d write breakpoints based on viewport width — but the card might be narrow even on a wide screen (in a sidebar) or wide on a narrow screen (full-bleed).

Setting Up

The parent declares it a container:

.card-wrapper {
  container-type: inline-size;
}

inline-size means “watch the inline (usually width) dimension”.

Then write rules in @container:

@container (min-width: 500px) {
  .card {
    display: grid;
    grid-template-columns: 200px 1fr;
    gap: 1rem;
  }
}

Now .card lays out horizontally when its .card-wrapper parent is at least 500px wide. Doesn’t matter what the viewport is.

Naming Containers

For multiple containers at different levels, name them:

.sidebar { container-name: sidebar; container-type: inline-size; }
.main    { container-name: main;    container-type: inline-size; }

@container sidebar (min-width: 300px) {
  /* applies only inside .sidebar */
}

Container Query Units

cqw, cqh, cqi, cqb — like vw/vh but for the container:

@container (min-width: 400px) {
  .card-title {
    font-size: 5cqw;     /* 5% of the container's inline size */
  }
}

Fluid typography that scales with the container, not the viewport.

Container Queries vs Media Queries

Use container queries for…Use media queries for…
Components that appear in many contextsPage-level layout decisions
Reusable cards, sidebars, widgetsBody font size, base typography
Anything that should respond to its OWN sizeMobile vs desktop nav

Both are valid; they answer different questions.

Up Next

Media queries — the classic responsive tool.

Media Queries →