
How to correctly use if() in CSS
6/2/25About 2 minCSSArticle(s)blogcss-tip.comcss
How to correctly use if() in CSS 관련
CSS > Article(s)
Article(s)
CSS is adding a new way to express conditions using an if() syntax (w3c/csswg-drafts). 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)
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 */
}
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
- Dots loader using shape() A classic 3 dots loader created using the new shape(). June 24, 2025
- The future of hexagon shapes A new way to easily create hexagon shapes using corner-shape. June 12, 2025
- Arc shape with rounded edges A modern way to create arc shapes with rounded edges using minimal code. May 20, 2025
- SVG to CSS Shape Converter The easiest way to convert an SVG shape into a CSS one. May 12, 2025

How to correctly use if() in CSS
Learn how to easily fix an issue you will face when using if()