Sub topic 10
Variants and themes through custom property queries
Earlier chapters used containers to react to size. A container can also be queried for the computed value of a custom property. This chapter shows how to use that for component variants and themes, and where the approach breaks down.
This chapter assumes you know custom properties (--name and var()), how inheritance works for them, and how @container size queries pick their container. You should also be comfortable reading selector specificity.
What a style query asks
A size query asks how big the container is. A style query asks what a custom property computes to on the container. The syntax is @container style(--name: value).
.alert-region {
--tone: warning;
}
.alert {
border: 2px solid gray;
}
@container style(--tone: warning) {
.alert {
border-color: orange;
background: #fff4e0;
}
}<div class="alert-region">
<p class="alert">Your session expires in five minutes.</p>
</div>The .alert element has no class that names the variant. It gets the warning styling because an ancestor, .alert-region, has --tone: warning.
Two facts make this work:
- Every element is a style query container. You do not need
container-type. A style query can run against any ancestor without any declaration. - Custom properties inherit by default. Elements between the region and the
.alertalso compute--tone: warning, so the match does not depend on the alert being a direct child.
Why the ancestor, not the element
A style query never matches the element's own custom properties. The rule @container style(--tone: warning) { .alert { ... } } styles .alert only when a parent, grandparent, or further ancestor has the value. If you put --tone: warning on the .alert element itself, the rule does not apply to it.
This restriction avoids circular logic. A rule cannot change an element's custom property and then depend on that same property to decide whether it applies.
If you name a container in the query, as in @container card style(--tone: warning), the browser looks for the nearest ancestor with that container name, then tests its computed style. The name comes first and the style() function follows it.
How values are compared
The match is on computed values, and the details affect how you write variants.
- Unregistered properties compare as token streams.
warningmatcheswarning. Differences in whitespace are ignored, butWarningandwarningare different. - Registered properties (declared with
@property) compare after the browser computes them against their syntax. For a<length>property,1remand16pxmatch when the root font size is 16px. - Missing values do not match anything. If no ancestor sets the property,
style(--tone: warning)is false.
You can combine conditions with and, or and not:
@container style(--tone: warning) or style(--tone: danger) {
.alert {
font-weight: 600;
}
}
@container style(--tone: info) and style(--emphasis: high) {
.alert {
border-width: 4px;
}
}
@container not style(--tone: info) {
.alert {
border-style: solid;
}
}Mix and and or only with parentheses. The parser rejects an unparenthesized mix in one condition.
Treat style queries as equality tests on custom properties. Querying regular properties such as style(color: red) is not available in the browsers that implement style queries, and range comparisons like style(--n > 3) are not part of what shipped. If you need a numeric threshold, set a keyword property yourself and query the keyword.
Registering properties to constrain variants
An unregistered property accepts any text. A typo like --tone: warnning creates a valid value that simply never matches. A registered property can reject bad values and fall back to a default.
@property --density {
syntax: "compact | regular | roomy";
inherits: true;
initial-value: regular;
}
.list-region {
--density: compact;
}
.item {
padding: 0.75rem 1rem;
}
@container style(--density: compact) {
.item {
padding: 0.25rem 0.5rem;
}
}
@container style(--density: roomy) {
.item {
padding: 1.25rem 1.5rem;
}
}With this registration, --density: cozy is invalid for the syntax, so the property computes to regular. A list with no region sets --density to regular too, because that is the initial value. Authors get a defined default instead of an unmatched query.
The inherits: true line matters. A registered property with inherits: false would not pass the value down to descendants of the region, so items several levels deep would not see it.
Themes
A theme is a variant applied to a large region, often the whole page. Set one property at the region boundary and let components query it.
:root {
--theme: light;
}
[data-theme="dark"] {
--theme: dark;
}
.panel {
background: white;
color: #1b1b1b;
border: 1px solid #c8c8c8;
}
@container style(--theme: dark) {
.panel {
background: #1b1b1b;
color: #f2f2f2;
border-color: #555;
}
}<body data-theme="dark">
<section class="panel">Dark panel</section>
</body>The attribute and the property do different jobs. data-theme is the switch that JavaScript or the server sets. --theme is the value the CSS exposes to style queries. The :root rule gives every page a default, and the later [data-theme="dark"] rule overrides it because both selectors have equal specificity and the later one wins.
You can switch a sub-tree without touching the rest of the page:
<body data-theme="light">
<section class="panel">Light panel</section>
<aside data-theme="dark">
<section class="panel">Dark panel inside a dark aside</section>
</aside>
</body>The nearest ancestor decides. The panel inside the aside sees --theme: dark, and the first panel sees light.
When a theme is better as plain custom properties
For a pure color theme, you often do not need style queries. Declare --panel-bg and --panel-fg in the theme selector and use var() in the component. That is simpler and works in every browser with custom property support.
Style queries earn their place when a variant changes more than a value: different layout, different pseudo-element content, a hidden element, or a different set of declarations. A var() can substitute one value. A style query can swap a whole block of rules.
Combining style queries with size queries
A component can respond to both its available width and its variant. Nest the queries instead of joining them in one condition, because nesting has the broadest support and reads clearly:
.card-wrapper {
container: card / inline-size;
}
.card {
display: block;
}
@container card (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
@container style(--density: compact) {
.card {
gap: 0.5rem;
}
}
}Here the inner style query has no name, so it targets the nearest ancestor. Custom properties inherit, so that ancestor, usually .card-wrapper or something inside it, still reports the density set further up. Naming the container in the inner query is also valid. A named container must exist among the ancestors. If you name card, set --density on or above .card-wrapper, because the query reads the computed style of that named element.
A related gotcha: when .card-wrapper has container-type: inline-size, it is both a size container and a style container. A style query without a name can match it. A style query with the name card matches only that wrapper. Choose between these deliberately.
Fallbacks for browsers without style queries
Size queries and style queries shipped at different times. A browser that supports @container (min-width: ...) may still ignore style(). The whole @container style(...) rule is then dropped, so your base styles must stand alone.
- Write the unqualified styles as the default look, not as a broken state.
- For variants that carry meaning, such as an error message, add a second selector that does not depend on style queries, for example
.alert[data-tone="danger"]. Thedata-toneattribute is set in markup. - Keep the style query for progressive refinements, such as density or decorative theming.
.alert {
border: 2px solid gray;
}
.alert[data-tone="danger"] {
border-color: crimson;
}
@container style(--tone: warning) {
.alert {
border-color: orange;
}
}The @supports (container-type: inline-size) test from the previous chapter checks size containers. It does not tell you whether style() queries work. Check current browser support before you rely on style queries for anything essential.
Pitfalls
- Setting the property on the styled element. The element cannot query itself. Move the property to a wrapper, or restructure so the styled element is a child.
- Expecting a match from a property that does not inherit. A registered property with
inherits: falseis visible only on the element that sets it. Style queries read the ancestor's own value, so descendants further down will not match. - Case and spelling mismatches. Unregistered values are plain tokens. Register the property with a keyword syntax to catch typos.
- Using quotes inconsistently.
--tone: "warning"is a string token and does not matchstyle(--tone: warning). Pick one form and keep it. - Treating it as a general
:has()replacement. Style queries test inherited values from ancestors only. They cannot test what a descendant contains. - Leaving theme defaults out. If no ancestor sets
--theme, no theme query matches, and only your base styles apply. Set a default on:root.
Exercise
A page sets --theme: dark on <section class="card"> itself. The stylesheet has @container style(--theme: dark) { .card { background: black; } }. Why does the card stay unchanged, and what is the smallest fix?
Show answer
A style query reads the computed custom property of an ancestor, never the styled element itself. The .card element is not its own query container, so the rule does not match. Move --theme: dark to a wrapper around the card, or to :root, or restyle the card's children with the query instead.
Exercise
Write a registered property --size that accepts only small, medium or large, defaults to medium and inherits. Then write a style query that gives .badge a font size of 0.75rem when --size is small.
Show answer
@property --size { syntax: "small | medium | large"; inherits: true; initial-value: medium; } @container style(--size: small) { .badge { font-size: 0.75rem; } }