Sub topic 3
Style Queries with `@container style()`
Assume you know CSS selectors, the cascade, custom properties, and the clamp() function. A style query lets a descendant respond to a custom property on an ancestor container. It is useful for variants and themes.
Style queries with `@container style()`
Declare a container, then query one of its computed custom properties:
.alert-region {
container: alerts / inline-size;
--tone: warning;
}
.alert {
border: 2px solid gray;
padding: 1rem;
}
@container alerts style(--tone: warning) {
.alert {
border-color: orange;
background: #fff4e0;
}
}The query checks the nearest matching container named alerts. It matches when that container's computed --tone value is warning. The .alert element is a descendant, so it can receive the conditional styles.
Variants and themes through custom property queries
Custom properties can represent component variants without adding variant-specific selectors:
.card-region {
container: cards / inline-size;
--theme: dark;
}
.card {
color: #222;
background: white;
}
@container cards style(--theme: dark) {
.card {
color: white;
background: #222;
}
}A parent can set --theme: dark or another value. The component keeps one class name while its appearance changes.
Pitfalls and containment effects
- A container cannot query its own styles. Put the query on a descendant.
- The queried custom property must be set or inherited on the container. An unset property does not match.
container-type: inline-sizeenables inline-size containment. In shrink-to-fit or intrinsic layouts, the container can become narrower than expected because its contents no longer determine its inline size. Give it an available width,width, ormin-widthwhen needed.- Containment can affect sizing and formatting. Test percentages, intrinsic sizes, and overflow after adding it.
- Nested containers change resolution. An unnamed query uses the nearest suitable ancestor; a named query skips ancestors with other names.
Progressive enhancement with `@supports`
Keep the default style outside the feature query. Add container behavior only when supported:
.alert {
border: 2px solid gray;
padding: 1rem;
}
@supports (container-type: inline-size) {
.alert-region {
container: alerts / inline-size;
--tone: warning;
}
@container alerts style(--tone: warning) {
.alert {
border-color: orange;
background: #fff4e0;
}
}
}Exercise
Why does the style query belong on .alert instead of .alert-region?
Show answer
A container query styles descendants of the queried container, but a container cannot query itself.