Defines a conditional group rule that applies styles to a containment context.
@container: [ container-name ] | size-query | style-query | scroll-state {
... style declarations ...
}
Parameter |
Description |
Valid Values |
container-name |
Optional. Specifies the name of the container that the styles will be applied to. |
Custom identifier that represents any valid CSS identifier. |
size-query |
A valid CSS size query in parentheses. |
( width | height | inline-size | block-size | aspect-ratio | orientation = | > | < value ) |
style-query |
A valid CSS style query in parentheses. |
style ( color: navy ) |
scroll-state |
A valid CSS scroll state query in parenthesis. |
scroll-state ( stuck | snapped | scrollable : value ) |
The @container at-rule is a conditional group rule, meaning styles are applied only to the container when the given condition evaluates to true.
The @container condition is specified as a container-query, and optionally with a container-name. A container-query must define either a size and/or a style query in parentheses. For example:
/* with a size-query */
@container ( width > 400px ) {
h2 {
font-size: 1.5em;
}
}
/* with optional container-name */
@container tall ( height > 30rem ) {
p {
line-height: 1.6;
}
}
Style declarations are filtered by these conditions and applied to the container only if the condition is true.
A container-query may also define scroll-state queries in parentheses. For example:
/* with a scroll-state query */
@container scroll-state( scrollable: top ) {
.back-to-top-link {
visibility: visible;
}
}
/* with a container-name and a scroll-state query */
@container sticky-heading scroll-state( stuck: top ) {
h2 {
background: purple;
color: white;
}
}
Logical keywords can also be used to combine or negate the container condition:
- and combines two or more conditions.
- or combines two or more conditions.
- not negates the condition. Only one not condition is valid per container query and cannot be used with the and or or keywords.
/* Multiple queries in a single condition */
@container ( width > 400px ) and style ( --responsive: true ) {
h2 {
font-size: 1.5em;
}
}
NOTE: This section is currently under major reconstruction. Please bear with whatever inconvenience you may encounter; we hope to complete the job at the soonest possible time.
External reference: CSS Conditional Rules Module Level 5