For years, CSS has grown from a basic style language into a powerful design tool. With features like variables, custom properties, and @supports
, we’ve been inching closer to something developers have always wished for: true conditional logic in CSS.
Now, it’s finally happening.
Introducing the new if()
function in CSS. A game-changer that adds programmatic decision-making to your styles.
What is the if() Function in CSS?
The if()
function allows you to conditionally apply values within CSS based on logical comparisons. Think of it as an if
statement in JavaScript, but for styles:
width: if(var(--is-narrow) == 1, 100px, 300px);
In this example, if --is-narrow
is equal to 1
, the width will be 100px
; otherwise, it will be 300px
.
This brings CSS one step closer to becoming a fully dynamic stylesheet language.
Syntax Overview
if(condition, value-if-true, value-if-false)
- Condition: A comparison using CSS variables, constants, or functions.
- Value-if-true: The value to apply if the condition evaluates to true.
- Value-if-false: The fallback or alternate value.
Example
:root {
--theme-dark: 1;
}
body {
background-color: if(var(--theme-dark) == 1, black, white);
color: if(var(--theme-dark) == 1, white, black);
}
This lets you dynamically change themes with just a variable toggle.
Why if() is a Big Deal
1. Dynamic Styling Without JS
No more bloated JavaScript just to switch styles based on a variable. Now, it’s pure CSS.
2. Cleaner Logic
No need for hacks like calc() based conditionals or clunky @media tricks when you just want a simple “if this, then that” scenario.
3. Better Theming and Responsiveness
Combine with custom properties to power light/dark mode, layout tweaks, accessibility features, and more.
Browser Support?
The if()
function is part of the CSS Conditional Rules and is now natively supported in Chrome-based browsers (137 and above), making it safe to experiment and use in projects that target those environments.
The if()
function is more than just a shiny new tool—it’s a shift in how we think about CSS logic. As this feature matures, we’ll be writing styles that are not only declarative but also smart and adaptive right out of the box.