Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

CSS Container Queries vs Media Queries: How to Build Responsive Components

A product card fits in a catalog but breaks when reused in a sidebar. Adding viewport breakpoints cannot solve the underlying problem if both cards appear on the same screen. Container size queries allow components to respond to the space allocated to them. The examples below separate page-level layout from component-level layout and explain how to diagnose a query that does not apply.

Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

When is a media query the right tool?

FeatureMedia queriesContainer size queries
ReferenceViewport or environmentEligible ancestor
Typical usePage layout, print, preferencesCard, widget, panel
Container requiredNoYes
Two cards on one screenSame conditionIndependent conditions
<div class="page">
  <aside class="sidebar">Filters</aside>
  <main class="results">Results</main>
</div>
.page {
  display: grid;
  gap: 1rem;
}

@media (min-width: 64rem) {
  .page {
    grid-template-columns: 16rem minmax(0, 1fr);
  }
}

The outer page layout depends on the available viewport. In this example filters and results are stacked until 64rem, when a 16rem sidebar appears. minmax(0, 1fr) lets the results track shrink, although its content still needs overflow handling. [4]

This rule says nothing about an individual card. At a viewport width of 1200px, a 280px sidebar card and a 560px main-area card would receive the same media-query rules. Container queries distinguish those cases without detecting devices.

How can identical cards have different layouts on the same screen?

<div class="card-slot narrow">
  <article class="product-card">
    <div class="product-image" aria-hidden="true"></div>
    <div class="product-body">
      <h2>Desk lamp</h2>
      <p>Adjustable brightness</p>
    </div>
  </article>
</div>

<div class="card-slot wide">
  <article class="product-card">
    <div class="product-image" aria-hidden="true"></div>
    <div class="product-body">
      <h2>Desk lamp</h2>
      <p>Adjustable brightness</p>
    </div>
  </article>
</div>
.card-slot {
  container-type: inline-size;
  max-inline-size: 100%;
}

.narrow {
  inline-size: 280px;
}

.wide {
  inline-size: 560px;
}

.product-card {
  display: grid;
  gap: 1rem;
  padding: 1rem;
  border: 1px solid #94a3b8;
}

.product-image {
  min-block-size: 7rem;
  background: #e2e8f0;
  border-radius: 0.5rem;
}

.product-body {
  min-inline-size: 0;
  overflow-wrap: anywhere;
}

@container (inline-size >= 480px) {
  .product-card {
    grid-template-columns: 9rem minmax(0, 1fr);
    align-items: center;
  }
}

Set container-type: inline-size on the wrapper. The default card stacks its image and text; at 480px the component switches to two columns. In horizontal writing mode the query measures the container's content width, excluding padding and borders. With slots of 280px and 560px only the second card changes. [1][2]

Derive breakpoints from content. At a 16px root font size, the image track consumes 144px, the gap 16px, padding 32px and borders 2px. That leaves about 286px for text in a 480px slot. Increase the threshold if localized content needs more room. minmax(0, 1fr) and overflow-wrap help handle long strings.

How do named containers work when nested?

<div class="dashboard">
  <div class="widget-slot">
    <article class="widget">
      <h2>Revenue</h2>
      <p>Monthly overview</p>
    </article>
  </div>
</div>
.dashboard {
  container: dashboard / inline-size;
  inline-size: 800px;
  max-inline-size: 100%;
}

.widget-slot {
  container: widget / inline-size;
  inline-size: 260px;
  max-inline-size: 100%;
}

.widget {
  padding: 8px;
  border: 1px solid #94a3b8;
}

@container dashboard (inline-size >= 700px) {
  .widget {
    border-width: 2px;
  }
}

@container widget (inline-size >= 400px) {
  .widget {
    padding: 24px;
  }
}

An unnamed size query selects the closest eligible ancestor. Here the widget slot is 260px wide and the dashboard is 800px wide. The named dashboard condition sets a 2px border, whereas the widget condition does not increase padding to 24px. Both conditions are independent. [2][5]

Name containers according to their responsibility, such as dashboard or widget. If several ancestors share a name, the closest eligible one is selected, not the first ancestor that passes the threshold. Distinct names prevent accidental coupling.

How can typography and spacing scale with the component?

<div class="panel panel-small">
  <h2 class="panel-title">Activity</h2>
</div>

<div class="panel panel-large">
  <h2 class="panel-title">Activity</h2>
</div>
.panel {
  container-type: inline-size;
  max-inline-size: 100%;
}

.panel-small {
  inline-size: 240px;
}

.panel-large {
  inline-size: 600px;
}

.panel-title {
  font-size: 1rem;
  font-size: clamp(1rem, 0.75rem + 2cqi, 2rem);
  line-height: 1.4;
  overflow-wrap: anywhere;
}

1cqi represents one percent of a container's inline dimension. With a 16px root font size, 0.75rem + 2cqi evaluates to 16.8px in a 240px panel and 24px in a 600px panel. Both fall inside clamp(1rem, ..., 2rem). [6]

Without an eligible ancestor, the unit falls back to the small viewport dimension for that axis. A name in an @container rule does not automatically change the reference used by cqi. Check fluid typography with text enlargement, long translations and different user font preferences.

Why can container-type change an element's size?

<div class="chart-slot">
  <div class="chart" role="img" aria-label="Illustrative chart">
    <span class="bar"></span>
  </div>
</div>
.chart-slot {
  container: chart / size;
  inline-size: 100%;
  max-inline-size: 36rem;
  block-size: 18rem;
}

.chart {
  display: grid;
  align-items: end;
  block-size: 100%;
  background: #e2e8f0;
}

.bar {
  inline-size: 3rem;
  block-size: 50%;
  background: #2563eb;
}

@container chart (block-size >= 16rem) {
  .bar {
    block-size: 75%;
  }
}

inline-size restricts the contribution of descendants to intrinsic inline sizing; size restricts both axes. This prevents feedback between descendant styling and the queried dimensions. A shrink-to-fit wrapper or a box with an automatic height may become unexpectedly small when size containment is enabled. [3]

The chart has an explicit height of 18rem, making its 16rem block-size threshold predictable. Prefer inline-size for cards whose height should follow content. To style the chart slot based on its own dimensions, introduce an outer query container and style the inner box instead.

Can Grid and Flexbox replace container queries?

<div class="catalog">
  <div class="catalog-slot">
    <article class="catalog-card">
      <div class="preview" aria-hidden="true"></div>
      <p>Product A</p>
    </article>
  </div>
  <div class="catalog-slot">
    <article class="catalog-card">
      <div class="preview" aria-hidden="true"></div>
      <p>Product B</p>
    </article>
  </div>
</div>
.catalog {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1rem;
}

.catalog-card {
  display: grid;
  gap: 0.75rem;
  padding: 1rem;
  border: 1px solid #94a3b8;
}

.preview {
  min-block-size: 5rem;
  background: #e2e8f0;
}

@supports (container-type: inline-size) {
  .catalog-slot {
    container-type: inline-size;
  }

  @container (inline-size >= 26rem) {
    .catalog-card {
      grid-template-columns: 7rem minmax(0, 1fr);
      align-items: center;
    }
  }
}

If the only requirement is an adaptive number of columns, Grid with repeat(auto-fit, minmax(...)) may be enough. Here the catalog allocates space without any query, and min(100%, 16rem) allows a single track to shrink below 16rem. Wrapping Flexbox is similarly useful for action bars.

A container query adds value when the card's internal structure needs to change. The base card is stacked; @supports enables the enhancement in browsers that recognize container-type: inline-size. This tests declaration support, not every query feature. Older browsers retain the usable base layout. [7]

How do both query types work together, and how can bugs be diagnosed?

<div class="action-slot">
  <div class="actions">
    <button type="button">Save</button>
    <button type="button">Cancel</button>
  </div>
</div>
.action-slot {
  container: actions / inline-size;
  inline-size: 100%;
  max-inline-size: 40rem;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.actions button {
  padding: 0.75rem 1rem;
  white-space: normal;
  overflow-wrap: anywhere;
  transition: background-color 150ms ease;
}

@container actions (inline-size >= 24rem) {
  .actions {
    flex-direction: row;
    flex-wrap: wrap;
  }
}

@media (prefers-reduced-motion: reduce) {
  .actions button {
    transition: none;
  }
}

The actions switch from a column to a wrapping row once the slot reaches 24rem. Long labels can wrap. Reduced-motion preferences are unrelated to component width, so @media (prefers-reduced-motion: reduce) removes the transition. DOM order and available actions remain unchanged. [4][9]

When a rule fails, look for the container badge in Chrome DevTools Elements and inspect the descendant in Styles. Measure the content box, confirm the name, type and axis, then inspect Computed for a competing declaration. Keep the viewport fixed while changing the component's allocated space. Style queries, such as style(--density: compact), are a different mechanism; verify support before using them. [8][10]

Media queries remain useful for page layouts and user preferences. Container queries allow individual components to respond independently. Let the outer Grid or Flexbox layout allocate space, then let the inner component adapt to it. This reduces dependencies on particular pages without multiplying component variants.

Tools for this topic

CSS Container Queries Media Queries Responsive Design CSS Layout Container Units Progressive Enhancement DevTools

Frequently asked questions

Do container queries replace media queries?

No. Container queries solve local layout problems; media queries still handle page-level layout, print and user preferences. [4]

Why does @container not style the container itself?

A size query selects an eligible ancestor of the styled element, not that element. Add a wrapper or move layout styles to a descendant. [2]

Do I need JavaScript or ResizeObserver?

Not for size-dependent CSS styling. Use ResizeObserver when dimensions are needed in JavaScript logic, such as recalculating a chart.

How should I choose a container breakpoint?

Find the minimum space needed for the component's content in that layout. Test long labels, translations and text enlargement rather than copying device breakpoints.

Sources and references

  1. MDN, CSS container queries↩1↩2
  2. W3C, CSS Conditional Rules Module Level 5↩1↩2↩3↩4
  3. MDN, container-type↩1↩2
  4. MDN, Using media queries↩1↩2↩3↩4
  5. MDN, container-name↩1↩2
  6. MDN, CSS length units↩1↩2
  7. MDN, @supports↩
  8. Chrome DevTools, Inspect and debug CSS container queries↩
  9. W3C WAI, C39: prefers-reduced-motion↩
  10. MDN, Using container size and style queries↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning