Container-name
Learn named containers with container-name.
Naming with container-name
A page can hold more than one container. Anonymous @container queries listen to the nearest container, which can pull in an outer container you did not mean. The container-name property gives a container a name.
Once named, you target the query as @container name (min-width: 200px). Only the container carrying that name drives the query; others are ignored.
This prevents confusion in nested layouts and keeps queries readable.
Nested named containers
When you name nested containers, queries target sharply. Give the outer container container-name: page and the inner one container-name: panel; then @container panel (min-width: 300px) runs only on the inner container's width.
Reusing a name across containers is allowed; the query picks the nearest container carrying that name. Still, unique names make a layout more predictable.
Exercise Write a named container query
Give the .side selector container-type: inline-size and container-name: side. Then, inside an @container side (min-width: 280px) query, set display: grid on the .side-list sub-selector. The list shows one column in a narrow container and a grid in a wide one.
Show example solution
/* open the side container and name it */
/* turn the list into a grid in wide containers */
.side {
container-type: inline-size;
container-name: side;
}
@container side (min-width: 280px) {
.side-list {
display: grid;
}
}
Test yourself
-
Which one queries a named container?
- @container (min-width: 200px)
- @container (name: sidebar)
- @container sidebar (min-width: 200px)
- @container (sidebar: min-width)
Show answer
@container sidebar (min-width: 200px) — Correct. The name comes right after @container, then the condition.
-
Complete the named query
@container ____ (min-width: 200px) { .menu { display: flex; } }Show answer
@container sidebar (min-width: 200px) { .menu { display: flex; } } -
Match the naming pieces
- container-name
- Property that names the container
- @container main
- Queries the container named 'main'
- main sidebar
- Example of multiple names
- container-type
- Property that opens the container