How to Use the CSS if() Function Correctly
Originally published in Turkish. Read the original →

A detailed guide to using the new CSS if() function correctly and the pitfalls to watch out for.
How to Use the CSS if() Function Correctly
The if() function, added to CSS with Chrome 137, offers a powerful way to express conditional values. The function accepts condition-value pairs and returns the value of the first condition that is true.
Basic Syntax
.box {
--theme: dark;
background: if(style(--theme: dark), black, white);
color: if(style(--theme: dark), white, black);
}
The Problem with Computed Values
There is one situation to be careful about when working with computed values:
.box {
--n: 6;
--f: calc(var(--n) / 2); / we expect this to be 3 /
background: if(style(--f: 3), red, green); / We get green! /
}
Why green? Because the value of --f has not been computed yet.
Why This Happens
This can be confusing, but the fix is quite simple. For the browser to perform the calculation, you need to register the value using @property. Otherwise, the browser sees the value as is (as if it were a string value).
Correct Usage
Register it with @property so computed values work correctly:
@property --f {
syntax: "<number>";
inherits: false;
initial-value: 0;
}
.box {
--n: 6;
--f: calc(var(--n) / 2); / Now it really is 3 /
background: if(style(--f: 3), red, green); / We get red /
}
More Examples
Theme Switching
.card {
--theme: light;
background: if(
style(--theme: dark),
#333,
style(--theme: light),
#fff,
#f0f0f0 / default /
);
}
Numeric Comparisons
@property --count {
syntax: "<integer>";
inherits: false;
initial-value: 0;
}
.notification {
--count: 5;
display: if(style(--count: 0), none, block);
background: if(style(--count: 0), transparent, red);
}
Simple Conditions
.button {
--disabled: false;
opacity: if(style(--disabled: true), 0.5, 1);
cursor: if(style(--disabled: true), not-allowed, pointer);
}
Browser Support
The CSS if() function is currently supported only in Chrome 137+. Don't forget to use fallback values for other browsers:
.box {
/ Fallback /
background: gray;
/ For modern browsers /
background: if(style(--theme: dark), black, white);
}
Summary
- Syntax:
if(condition, value1, condition2, value2, default) - Computed values: require registration with
@property - Browser support: Chrome 137+ (as of 2025)
- Fallback: provide alternative values for older browsers
The CSS if() function lets you write conditional styles in a cleaner, more readable way. When working with computed values, don't forget the @property registration, and use fallback values to cover browser support.




