typestar

Variables with a fallback in CSS

The second argument of var() is what to use when the variable is not set.

.stack {
  display: grid;
  gap: var(--stack-gap, 1rem);
}

.stack.tight { --stack-gap: 0.25rem; }
.stack.loose { --stack-gap: 2rem; }

.button {
  --button-bg: #2b6cb0;
  background: var(--button-bg);
  padding: var(--button-padding, 0.5rem 1rem);
  border-radius: var(--radius, 0.375rem);
}

.button.danger { --button-bg: #dc2626; }

How it works

  1. var(--gap, 1rem) uses 1rem until something defines --gap.
  2. A variable set on a class only applies inside that subtree.
  3. An invalid variable value makes the whole declaration invalid at computed time.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
322
Tokens
87
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 2 of 3 in Custom properties, step 6 of 21 in Responsive & modern CSS.

← Previous Next →