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 should get a red color */
}
The color is red, right? No, it's green! For the browser --f is equal to calc(var(--n)/2). It doesn't perform the calculation and considers it like a string matching.
See the Pen Untitled by Temani Afif (@t_afif) on CodePen.
This can be confusing, but the fix is quite easy. You register the custom property using @property and the browser will perform the calculation.
@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 you have no calculation and you only want an exact match like the examples below:
.box {
--f: error;
background: if(style(--f: error): red; else: green);
}
.box {
--v: 0;
background: if(style(--v: 0): red; else: green);
}
We can also use = instead of : in the first example, and it works without the need to register the custom property:
.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 */
}
I am detailing this last example in the following post: The Hidden Trick of Style Queries and if()
More CSS Tips
- Dots loader using shape() A classic 3 dots loader created using the new shape().
- The Future of Hexagon Shapes A new way to easily create hexagon shapes using corner-shape.
- Arc shape with rounded edges A modern way to create arc shapes with rounded edges using minimal code.
- SVG to CSS Shape Converter The easiest way to convert an SVG shape into a CSS one.