CSS Container Queries
Written by: Avinash Malhotra
Updated on
What are CSS container queries?
CSS container queries let a component respond to the size of its nearest query container instead of the browser viewport. This makes a component reusable in a sidebar, grid, dialog, or full-width layout without needing separate page-level breakpoints.
Media queries are still useful for changing the page layout. Use container queries when the component itself needs to adapt to the space available inside its parent. A container query is written with @container, while a viewport query is written with @media.
Container Types
The container-type property defines which dimensions an element exposes to container queries:
- inline-size: Queries the container's inline dimension, usually its width in a horizontal writing mode. This is the most common choice for responsive components.
- size: Queries both the inline and block dimensions of the container.
- normal: The default value. The element is not a size query container, although it can still support other container-query features such as style queries.
For width-based responsive behavior, use inline-size. Use size only when the query also needs to evaluate the container's block dimension.
section{
container-type: inline-size;
}
Container Name
Use container-name to give a query container an explicit name. A named container is useful when a component has more than one possible ancestor container and the query should target a specific one.
section{
container-type: inline-size;
container-name: my-container;
}
The container shorthand
The container property is shorthand for container-name and container-type. Its value uses the form name / type, so the following declaration creates a container named my-container that exposes its inline size.
section{
container: my-container / inline-size;
}
Writing @container queries
The @container rule applies styles to descendants when the selected container matches a condition. The container establishes the responsive boundary; the queried element must be inside that container.
This example changes the background of a child element when the named container is at least 500 pixels wide:
@container my-container (min-width: 500px) {
.card {
background-color: lightblue;
}
}Responsive card example
This example makes a product card stack vertically in a narrow container and arrange horizontally when more inline space is available. Drag the right edge of the demo to resize the container.
Product 1
Product 2
Product 3
Resize the container to see the card layout change.
.products{
container: products / inline-size;
padding: 1rem;
border: 1px solid #ccc;
}
.card{
display: flex;
border: 1px solid #ccc;
}
@container products (max-width: 460px) {
.card {
flex-direction: column;
}
}
@container products (min-width: 461px) {
.card {
flex-direction: row;
}
}