Understanding CSS container-name and container-type
CSS Container Queries allow elements to adapt their styles based on
the dimensions of a parent container rather than the overall browser
viewport. The container-type property turns an element into
a queryable container, while the container-name property
assigns a unique identifier to that container. Used together, they
enable precise component-based styling, allowing developers to target
specific ancestor containers even within deeply nested layouts.
What is container-type?
Before an element can be queried using @container rules,
it must be established as a containment context. The
container-type property defines what aspects of the
container can be measured:
normal: The default value. The element is not a query container for dimensional queries, but it can still be queried for computed styles.inline-size: Establishes a container query context based on the element's inline axis (width in horizontal writing modes). This is the most common value used for responsive layouts.size: Establishes a query context based on both the inline and block axes (width and height).
.card-wrapper {
container-type: inline-size;
}What is container-name?
When multiple container contexts are nested, an
@container rule targets the nearest ancestor
container by default. The container-name property allows
you to assign an arbitrary name (an <ident>) to a
container context.
Naming containers lets you bypass the nearest ancestor and target a specific container higher up in the DOM tree.
.sidebar {
container-name: sidebar;
}
.card-wrapper {
container-name: card;
}Combining container-name and container-type
To create a named query container, you apply both properties to the
target parent element. You can declare them separately or use the
container shorthand property.
Separate Declarations
.profile-widget {
container-name: profile;
container-type: inline-size;
}The container
Shorthand
The shorthand property accepts the name and the type separated by a
forward slash (name / type):
.profile-widget {
container: profile / inline-size;
}Querying Named Containers
Once a container has both a type and a name, you reference the name
directly in your @container rule:
@container profile (min-width: 400px) {
.user-avatar {
width: 80px;
height: 80px;
}
.user-bio {
display: block;
}
}If the name is omitted in the query (for example,
@container (min-width: 400px)), CSS resolves the styles
against the closest ancestor that has a valid
container-type, regardless of its name. Specifying the name
guarantees that styles will apply only when that specific container
context meets the condition, preventing unintended overrides in complex,
nested component structures.