5.2 · Logic in CSS

Inline conditions: if()

Choose a value inline, based on a condition, right in the declaration.

if() chooses a value inside a single declaration. Conditions can be style() for custom properties, media() for media queries and supports() for feature checks. The first true branch wins, and else catches the rest.

It applies to the element itself, so there’s no container needed. Put a plain declaration before it as the fallback for browsers that don’t support it yet.

Before
.button { background: purple; }
.button--danger { background: crimson; }
.button--ghost { background: none; }
@media (width < 30rem) {
  .button { border-radius: 99rem; }
}
Now
.button {
  background: if(
    style(--variant: danger): crimson;
    style(--variant: ghost): transparent;
    else: purple
  );
  border-radius: if(
    media(width < 30rem): 99rem; else: 0.5rem
  );
}