Chrome Adds Support for if()
Functions in CSS
Photo Credits: Chrome For Developers
The if()
function is part of the CSS specification and is described in the section the if() notation. While it’s part of the standard, it’s still in draft status. Chrome is the first browser to implement support for this function.
Syntax
The if()
function provides a concise way to express conditional values. It accepts a series of condition-value pairs, separated by semicolons.
The function evaluates each condition in order and returns the value associated with the first condition that evaluates to true. If none of the conditions are true, the function returns an empty token stream.
Syntax:
selector {
color: if(
style(<condition>): <value>;
style(<another-condition>): <value>;
else: <value>;
);
}
Example:
div {
color: var(--color);
background-color: if(
style(--color: white): black;
else: white
);
}
.dark {
--color: black;
}
.light {
--color: white;
}
Is It Cool?
Yes! While we’re still waiting for pattern matching in JavaScript, it’s already landed in CSS.
But really, why is it cool? if()
in CSS is an expression, which means it returns the result of its internal logic when called. Unlike the if statement in JavaScript, where if()
is a control structure rather than an expression. In that sense, it’s closer to the ternary operator than to the classic if.
Browser Support
At the time of writing, the if()
function is supported in Chrome version 137 and above. Other browsers haven't caught up yet. The Firefox camp is here, and for the Apple folks, this way.