Stop Writing .btn--primary: CSS if() Kills Variant Class Explosions

October 9, 2026  |  9 min read  |  CSS

By Syed · Frontend Engineer & Creator of UITweak

Every design system ends up here: .btn, .btn--primary, .btn--danger, .btn--ghost, .btn--lg, .btn--primary.btn--lg, and a JavaScript helper whose only job is toggling those classes. The CSS if() function collapses all of that into a single rule block. You set a custom property like --variant: primary on the button, and if(style(--variant: primary): ...) picks the right value per property, re-evaluated live by the browser. No modifier classes, no class toggling, no Sass mixin that bakes the decision in at compile time.

30-second version: if() branches a property value on three condition types: style() (custom property value), media() (inline media query), supports() (inline feature query). First match wins, else: is the fallback. Chrome 137+ only, so ship the classic classes as the default and layer if() behind a @supports guard.

The Variant-Soup Problem the CSS if() Function Solves

A button with four variants and three sizes is not twelve classes in theory. In practice it is worse: the combinatorial classes (.btn--primary.btn--lg), the overrides when two modifiers fight over padding, and the framework code that computes class strings from props. Utility frameworks paper over it with generated class soup; Sass papered over it with mixins. Both bake the decision before the browser ever runs.

if() moves the decision into the browser. The variant becomes data (style="--variant: primary"), and the stylesheet becomes a set of branches per property. Change the custom property in DevTools or with one line of JS and the button restyles instantly, because the condition is re-evaluated live. That is the whole pitch: variants as state, not as class names.

The CSS if() Function in 60 Seconds: Syntax

The shape is one function with semicolon-separated branches. Each branch is condition: value, and else: catches everything unmatched:

background: if(
  style(--variant: primary): #2563eb;
  style(--variant: danger): #dc2626;
  else: #e5e7eb
);
  • style(--variant: primary) reads a custom property value. This is the variant engine.
  • media(width >= 768px) takes any media condition, evaluated inline instead of in a separate @media block.
  • supports(display: grid) takes any feature query, evaluated inline instead of in a separate @supports block.
  • Branches are checked top to bottom and the first match wins, like an if / else-if chain.
  • No space between if and the parenthesis. if ( with a space is invalid and the whole declaration is dropped.
  • Branches are separated by semicolons, not commas, so commas stay legal inside values like rgb(). The final semicolon is optional.

The point that trips everyone up: style() inside if() reads the custom property on the element itself. No container query context is needed. That is the deliberate difference from @container style()queries, which test a container. Here, --variant set inline on the button (or inherited from a parent) is what the branch checks.

Recipe 1: One .btn Rule for Every Variant

Design your base button once, then let branches carry the variants. A fast way to get the base right is uitweak’s Tailwind button generator: dial in padding, radius, font weight, and shadow on sliders, copy the CSS, and paste it in as the.btn foundation. The generator handles the static half; the recipe below handles the variant half that used to need six more classes. If you want the written walkthrough of button styling fundamentals first, our Tailwind button guide covers it.

/* one rule block, four variants, zero modifier classes */
.btn {
  --variant: default;

  padding: 0.625rem 1.25rem;
  border-radius: 0.5rem;
  font-weight: 600;
  border: 1px solid transparent;
  cursor: pointer;

  background: if(
    style(--variant: primary): #2563eb;
    style(--variant: danger): #dc2626;
    style(--variant: ghost): transparent;
    else: #e5e7eb
  );
  color: if(
    style(--variant: primary): #ffffff;
    style(--variant: danger): #ffffff;
    style(--variant: ghost): #2563eb;
    else: #111827
  );
  border-color: if(
    style(--variant: ghost): #2563eb;
    else: transparent
  );
}
<button class="btn" style="--variant: primary">Save changes</button>
<button class="btn" style="--variant: danger">Delete account</button>
<button class="btn" style="--variant: ghost">Cancel</button>
<button class="btn">Default</button>

Notice what disappeared: there is no .btn--primary rule, no btnClass(variant, size) helper, no prop-to-class mapping in your component. The HTML carries state (--variant); the CSS carries the branching. Picking readable text colors per variant is its own small problem, and our contrast-color() button text guide shows how to automate that choice instead of hardcoding white everywhere.

Recipe 2: Combine Conditions Without Nested Rules

Variants are only the start. Each property gets its own branch list, so size, density, and input method compose without combinatorial classes:

.btn {
  --size: md;

  padding: if(
    style(--size: sm): 0.375rem 0.75rem;
    style(--size: lg): 0.875rem 1.75rem;
    else: 0.625rem 1.25rem
  );
  font-size: if(
    style(--size: sm): 0.8125rem;
    style(--size: lg): 1.0625rem;
    else: 0.9375rem
  );

  /* touch targets, decided inline per property */
  min-height: if(
    media(any-pointer: coarse): 44px;
    else: 36px
  );
}

if() can also return just part of a value inside shorthands, which keeps the fixed parts fixed and branches only what changes:

/* only the color branches; width and style stay put */
.callout {
  border: 2px solid if(
    style(--tone: danger): #dc2626;
    style(--tone: warning): #d97706;
    else: #d1d5db
  );
}

/* works inside calc() too */
.panel {
  width: calc(if(style(--wide: true): 70%; else: 50%) - 2rem);
}

Two limits to respect. First, if() is a value, not a selector: it does not change specificity, so .btn with branches still loses to .btn.is-active exactly as before. Second, the spec does not allow nesting an if() inside another if(). If a branch needs two conditions at once, write both checks as separate branches in one flat list, since first-match-wins already gives you priority ordering.

Recipe 3: Inline media() and supports() Fallbacks

The other two condition types replace the tiny @media and @supports blocks that used to be duplicated per component. A one-property feature fallback that previously needed a wrapper block becomes one declaration:

.hero {
  /* modern color space where supported, safe hex elsewhere */
  background: if(
    supports(background: oklch(0.7 0.15 250)): oklch(0.7 0.15 250);
    else: #3b82f6
  );
}

.card {
  /* dark mode without a separate @media block */
  background: if(
    media(prefers-color-scheme: dark): #111827;
    else: #ffffff
  );
  color: if(
    media(prefers-color-scheme: dark): #f3f4f6;
    else: #111827
  );
}

Rule of thumb: style() is for your own state (variants, sizes, themes you toggle), media() is for the environment (viewport, pointer, color scheme), and supports() is for capability fallbacks. Mixing them in one if()is legal, since branches are just an ordered list, but keep each property’s list readable. Three branches is comfortable; eight is a sign the logic belongs in separate rules.

The Live Part: No More JS Class Toggles

The payoff over Sass mixins is reactivity. Sass conditionals resolve at compile time; if() resolves at runtime, and the browser re-evaluates whenever the inputs change. Swap a variant with one line and no class list to sync:

// swap a variant without touching classList
document.querySelector(".btn")
  .style.setProperty("--variant", "danger");

Try it in DevTools right now: open a page using Recipe 1, select a button in Elements, and edit --variant: primary to --variant: danger in the Styles panel. The background, text color, and border update instantly. Media branches react the same way: resize the window and a media(any-pointer: coarse) branch flips the moment the condition changes. Hover states stay where they belong, in :hover rules, since if() handles variants and pseudo-classes handle interaction. Our button hover effects guide covers that half of the story.

CSS if() Function Browser Support: The Honest Matrix

Several tutorials claim Safari 18.4 shipped if(). That claim is wrong. Here is the matrix from caniuse, verified October 9, 2026:

  • Chrome 137+: supported (shipped May 2025). Chrome for Android too.
  • Edge 137+: supported.
  • Opera 121+: supported.
  • Safari: not supported in any stable release, including Safari 26.x and the 27 previews tracked by caniuse. A preview implementation landed in Safari Technology Preview 249 (July 2026), which is where the 18.4 rumor started, but it has not shipped in stable Safari. iOS Safari is not supported either.
  • Firefox: not supported through Firefox 160. Implementation is tracked in Bugzilla bug 1981485, with no shipped version yet.
  • Samsung Internet: not supported.

MDN marks if() as limited availability and experimental, and caniuse reported roughly 65% global support back in June 2026. Translation: if() is a Chromium-only feature today. Do not make it load-bearing. The next section is the fallback recipe that lets you use it anyway.

The @supports Fallback Recipe

Ship the classic approach as the default, then layer if() on top behind a feature probe. The probe is a @supports declaration that itself contains an if(): browsers that parse it enter the block, browsers that do not skip it:

/* 1. fallback path: classic modifier classes, works everywhere */
.btn { /* base styles: padding, radius, font */ }
.btn--primary { background: #2563eb; color: #fff; }
.btn--danger  { background: #dc2626; color: #fff; }

/* 2. enhancement path: only browsers that parse if() */
@supports (background: if(style(--v: a): red; else: blue)) {
  .btn {
    --variant: default;
    background: if(
      style(--variant: primary): #2563eb;
      style(--variant: danger): #dc2626;
      else: #e5e7eb
    );
    color: if(
      style(--variant: primary): #ffffff;
      style(--variant: danger): #ffffff;
      else: #111827
    );
    /* same pattern for border-color, padding, and the rest */
  }
}
<!-- fallback markup keeps working when if() is absent -->
<button class="btn btn--primary" style="--variant: primary">
  Save changes
</button>

A small honesty note: the @supports wrapper is optional for simple cases. CSS already drops declarations it cannot parse, so a plain background: #e5e7eb followed by background: if(...) falls back for free in non-supporting browsers. Use the explicit @supports block when the fallback needs different structure, like modifier classes versus a single else: value. And in supporting browsers, always write else:: with no matching branch and no else, the declaration becomes an empty value and is dropped, which silently hands control back to whatever the cascade had before.

Gotchas That Break if() Silently

  • if ( with a space is invalid. The parser treats it as an unknown function and drops the declaration. No error, no warning.
  • Branches use semicolons, not commas. A comma inside a branch value (like rgb(37, 99, 235)) is fine; a comma between branches is not.
  • style() reads the element’s own custom property, or one inherited from an ancestor. It is not a container query; you do not need container-type anywhere.
  • Style queries compare token streams, so style(--variant: primary) matches the ident primary. A value of "primary" with quotes is a string and will not match.
  • No nesting: if() cannot appear inside another if() in the current spec. Flatten with ordered branches instead.
  • Newer Chromium builds also accept range comparisons like style(--level > 3) for numeric custom properties, but treat that as a bonus, not a baseline.

Recap

  1. Variant classes explode combinatorially. if(style(--variant: x): ...) replaces them with one rule block and state-as-data.
  2. Syntax: condition: value branches separated by semicolons, first match wins, else: is the catch-all, no space after if.
  3. style() reads the element’s own custom property. media() and supports() inline the queries you used to wrap in blocks.
  4. It re-evaluates live: DevTools edits and setProperty calls restyle instantly, no class toggling.
  5. Support is Chromium-only (Chrome/Edge 137+, Opera 121+). Safari and Firefox have not shipped it. Always ship the classic fallback first, if() behind @supports.

Related: if() handles the variant half of a button. The visual half, hover states, shadows, and text contrast, lives in our Tailwind button guide, button hover effects guide, and contrast-color() button text guide.

Frequently Asked Questions

Some tutorials say Safari 18.4 supports if(). Who is right?

Caniuse, checked October 9, 2026: no stable Safari release supports if(), desktop or iOS. A preview implementation appeared in Safari Technology Preview 249 in July 2026, and at least one tutorial read that as a shipped release. It was not. Treat Safari as unsupported until a stable version actually ships it, and keep the fallback recipe above in place.

Does if() change specificity or the cascade?

No. if() is a value inside a declaration, not a selector, so it adds zero specificity. .btn with if() branches still loses to .btn.is-active exactly the way a plain .btn rule does. The cascade around the declaration is unchanged; only the chosen value is conditional.

What happens when no branch matches and there is no else?

The if() resolves to an empty value, which makes the declaration invalid at computed-value time, so the browser drops it and the previous cascade value applies. That is occasionally useful (conditional removal of a property), but for variants it is a bug factory. Always write else:.

Share this guide