if() CSS Function
The if() function chooses a property value based on a condition, such as a style query, media query or supports test, written inline in the declaration.
Description
The if() CSS function lets a property value depend on a condition, written inline inside the declaration. It works like a chain of "if ... else if ... else" statements: the function checks each condition in order and uses the value paired with the first one that is true. If none match and there is no else branch, the declaration becomes invalid at computed-value time, just like an unresolved var().
Each branch is a condition, a colon, a value and a semicolon. Three kinds of condition are available. style() tests the value of a custom property on the element, for example style(--size: large). media() tests a media feature, such as media(width >= 700px). supports() tests whether the browser supports a declaration. The keyword else always matches and is used as the final fallback. Conditions can be combined with and, or and not.
/* Component variants driven by a custom property */
.button {
background: if(
style(--variant: danger): #dc2626;
style(--variant: success): #16a34a;
else: #2563eb
);
}
/* Responsive value without a separate media query block */
.card {
padding: if(media(width >= 700px): 2rem; else: 1rem);
}
/* Use a modern color if supported */
.title {
color: if(supports(color: oklch(0 0 0)): oklch(55% 0.2 260); else: #3b5bdb);
}
if() is a recent addition to CSS and is not yet supported in Firefox, so include a plain declaration before it as a fallback.
Interactive Demo
Syntax
if() = if( [ <if-branch> ; ]* <if-branch> ;? )
<if-branch> = <if-condition> : <declaration-value>?
<if-condition> = <boolean-expr[ <if-test> ]> | else
<if-test> = supports( ... ) | media( ... ) | style( ... )
Values
- <if-condition>A test to evaluate: style() for custom property values, media() for media queries, supports() for feature detection, or else, which always matches. Tests can be combined with and, or and not.
- <declaration-value>The value used when its condition is the first one that is true. It can be empty.
Example
Browser Support
The following information will show you the current browser support for the CSS if() function. Hover over a browser icon to see the version that first introduced support for this CSS function.
Desktop





Tablets & Mobile





