What is Container Query in CSS: Explained with Examples
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.
.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;
}
}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-typeon 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-type on the container to enable container queries.