Skip to main content
CSS Tip

How to correctly use if() in CSS

CSS is adding a new way to express conditions using an if() syntax. While it looks easy to use, there is a gotcha you should be aware of. Take the example below:

.box {
--n: 6; /* We define 6 */

--f: calc(var(--n)/2); /* the result is 3 */
background: if(style(--f: 3): red; else: green); /* We get a red color */
}

The color is red, right? No, it's green! For the browser the value of --f is equal to calc(var(--n)/2) (no calculation are made)

See the Pen Untitled by Temani Afif (@t_afif) on CodePen.

This can be confusing but the fix is quite easy. You have to register the value using @property so the browser can perform the calculation. Otherwise, the browser will see the value as it is (It's like a string value).

@property --f {
syntax: "<number>";
inherits: false;
initial-value: 0;
}

.box {
--n: 6; /* We define 6 */

--f: calc(var(--n)/2); /* the result is 3 */
background: if(style(--f: 3): red; else: green); /* We get a red color */
}

See the Pen Untitled by Temani Afif (@t_afif) on CodePen.

The registration is not required if there is no calculation and you want an exact matching like the below examples:

.box {
--f: error;
background: if(style(--f: error): red; else: green);
}

.box {
--v: 0;
background: if(style(--v: 0): red; else: green);
}

More CSS Tips