@container style() Query — Switch on a Custom Property Value

Use @container style() queries to apply child styles based on a parent's custom property value, enabling component variants driven by CSS variables instead of class names.

Basic Patterns

Detailed Explanation

Style Queries — Querying Properties, Not Just Size

Style queries are the second flavour of container query. Instead of asking "how wide is my container?" they ask "what value does this CSS property hold on my container?". As of 2024, browsers ship support for querying custom properties (--var) reliably; querying built-in properties is still being rolled out.

The CSS

.theme-host {
  --tone: "calm";
}

.theme-host[data-tone="alert"] {
  --tone: "alert";
}

@container style(--tone: "alert") {
  .badge {
    background: var(--error);
    color: white;
  }
}

@container style(--tone: "calm") {
  .badge {
    background: var(--surface);
    color: var(--text-muted);
  }
}

Why Not Just Use a Class?

Class-based variants couple presentation to markup, while style queries let a single source of truth (the custom property) drive an unlimited number of descendant styles. Toggle one variable on the host and dozens of nested elements respond — without touching their HTML.

Common Use Case: Theme Tokens

.card-host {
  --density: "comfortable";
}

.card-host.compact {
  --density: "compact";
}

@container style(--density: "compact") {
  .card { padding: 0.5rem; }
  .card h3 { font-size: 0.95rem; }
}

Limitations Right Now

  • Querying arbitrary built-in properties (e.g., background-color) is not widely shipping yet — stick to custom properties.
  • The container must declare the property; descendants inherit but the query evaluates against the container's computed value.
  • Safari 18+, Chrome 111+, Firefox 128+ support style queries on custom properties.

Pair with Size Queries

Style and size queries can coexist. A panel might be wide AND in alert mode:

@container (min-width: 500px) and style(--tone: "alert") {
  .alert-banner { padding-block: 1rem; }
}

Use Case

Use style queries to power theme variants, density modes, and stateful component skins driven by CSS variables. Especially powerful for design-system tokens where one host attribute should ripple through nested children.

Try It — CSS Container Query Builder

Open full tool