CSS if() Function for Inline Conditional Styles
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 feature queries (supports()).
The old hack vs the modern fix
View demo/* Multiple class variants */
.btn {
background: gray;
}
.btn.primary {
background: blue;
}
.btn.danger {
background: red;
}
/* Plus JS to manage state:
el.classList.toggle('primary', isPrimary); */
/* Duplicated rules per variant */.btn {
background: if(
style(--variant: primary): blue;
else: gray
);
}If browser support
Live demo
Why the modern way wins
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.
- Variants
- Inline
- No class toggling
- Old Approach
- JS + classes
- Multiple rule blocks
- Modern Approach
- if()
- Inline conditional
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.