Inline conditional styles without JavaScript
Conditional styling used to require JavaScript to toggle classes based on state. CSS if() lets you write inline conditions that respond to custom property values, media features, and container queries.
2.btn { background: gray; }
3.btn.primary { background: blue; }
4.btn.danger { background: red; }
5
6/* Plus JS to manage state */
7el.classList.toggle(
8 'primary',
9 isPrimary
10);
11
12/* Duplicated rules per variant */
2 background: if(
3 style(--variant: primary):
4 blue;
5 else: gray
6 );
7}
Inline conditions
Write if/else logic directly in property values. No separate rule blocks for each variant.
Style queries
Test custom property values with style(). Respond to --variant, --size, --state without JavaScript class management.
Media-aware
Can also test media features like prefers-color-scheme or prefers-reduced-motion right inside a property value.
How it works
Component variants have always required separate CSS rules: .btn.primary, .btn.danger, .btn.outlined, each repeating the same properties with different values. JavaScript often manages which classes are applied, adding another layer of complexity.
CSS if() lets you write conditional logic inline. A single .btn rule can test style(--variant: primary) and choose values accordingly. It can also test media features like prefers-color-scheme: dark directly inside a property value, eliminating the need for separate @media blocks for simple value swaps.