stackademic

The leading education platform for anyone with an interest in software development.

Container Queries

Style components based on their container's size rather than the viewport

Overview

Container queries let a component adapt to the size of its containing element instead of the global viewport, making truly reusable, context-aware components. You first mark an ancestor as a query container with container-type, then write @container rules against it. This decouples responsive behavior from page-level breakpoints, so the same card can render differently in a sidebar versus a full-width region.

Syntax / Usage

Declare a container with container-type: inline-size (and optionally a name via container-name), then target its size with @container. Size queries require inline-size or size; normal only enables style/container-unit features.

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

@container card (min-width: 400px) {
  .card {
    display: grid;
    grid-template-columns: 120px 1fr;
  }
}

Examples

A card that switches from stacked to side-by-side based on its own width:

<div class="card-wrapper">
  <article class="card">
    <img src="cover.jpg" alt="" />
    <div class="body">Title and text</div>
  </article>
</div>
.card-wrapper { container-type: inline-size; }

.card { display: block; }

@container (min-width: 350px) {
  .card {
    display: flex;
    gap: 1rem;
  }
}

Using container query units (cqi) to scale typography with the container:

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

.card h2 {
  font-size: clamp(1rem, 5cqi, 2rem);
}

Common Mistakes

  • Forgetting container-type, so @container rules never match
  • Querying a container from an element that isn't a descendant of it
  • Setting container-type: size without a defined block size, which can collapse content
  • Expecting the container itself to be styled by its own @container rule — only descendants respond
  • Mixing up container units (cqi, cqb) with viewport units (vw, vh)

See Also

responsive-design grid custom-properties