0
0
CssConceptBeginner · 3 min read

What is Container Query in CSS: Explained with Examples

A container query in CSS lets you apply styles to an element based on the size of its parent container instead of the whole viewport. This means you can make components adapt their look depending on the space they have, making designs more flexible and modular.
⚙️

How It Works

Think of a container query like checking the size of a box before deciding how to decorate it. Instead of looking at the whole room (the screen), you only look at the box (the container) that holds your item. If the box is small, you might choose a simpler decoration; if it's big, you add more details.

In CSS, container queries let an element change its style based on the size of its parent container. This is different from media queries, which look at the entire screen size. Container queries make components smarter and more reusable because they respond to their own space, not the whole page.

💻

Example

This example shows a box that changes its background color and text size depending on the width of its container.

css
.container {
  container-type: inline-size;
  width: 100%;
  max-width: 400px;
  border: 2px solid #333;
  padding: 1rem;
  margin-bottom: 1rem;
}

.box {
  background-color: lightcoral;
  font-size: 1rem;
  padding: 1rem;
  color: #222;
  transition: all 0.3s ease;
}

@container (min-width: 300px) {
  .box {
    background-color: lightgreen;
    font-size: 1.5rem;
  }
}
Output
<div class="container" style="width: 250px;"><div class="box">Small container</div></div> <div class="container" style="width: 350px;"><div class="box">Large container</div></div>
🎯

When to Use

Use container queries when you want components to adapt based on their own space, not the whole screen. This is great for building reusable UI parts that look good in different layouts, like cards inside grids or widgets in sidebars.

For example, if you have a card that appears in a narrow sidebar and a wide main area, container queries let the card change its layout or font size depending on where it is placed. This avoids awkward designs and keeps your site flexible.

Key Points

  • Container queries apply styles based on the size of a container, not the viewport.
  • They require setting container-type on the parent container.
  • They help build modular, reusable components that adapt to different spaces.
  • Supported in modern browsers like Chrome, Edge, and Firefox (latest versions).

Key Takeaways

Container queries let CSS styles depend on the size of a parent container, not the whole screen.
You must declare container-type on the container to enable container queries.
They make components flexible and reusable in different layouts.
Container queries are supported in modern browsers and improve responsive design.
Use container queries to adapt UI parts inside varying container sizes like cards or widgets.