Conditional values with CSS if()

Experimental Reference ↗

Choose a property value inside a declaration using if(). Here, a custom property selects compact spacing without adding a separate selector for the compact variant.

<style>
  .card {
    padding: 1.5rem;
    border: 1px solid currentColor;
  }

  @supports (padding: if(style(--density: compact): .5rem; else: 1.5rem)) {
    .card {
      padding: if(style(--density: compact): .5rem; else: 1.5rem);
    }
  }
</style>

<div class="card" style="--density: compact">Compact spacing</div>
<div class="card">Regular spacing</div>  

style(--density: compact) tests the custom property on the styled element. The else branch supplies the regular spacing. Semicolons separate branches inside the function.

This is CSS conditional syntax, not JavaScript. Conditions can use supported style, media or feature queries; they cannot evaluate arbitrary JavaScript expressions.

if() is experimental and has limited browser support. The @supports block keeps the original padding when the function is unavailable. The compact appearance is an enhancement, not a requirement for reading the card.