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
var(--gap, 1rem)uses 1rem until something defines--gap.- A variable set on a class only applies inside that subtree.
- An invalid variable value makes the whole declaration invalid at computed time.
Keywords and builtins used here
backgroundbuttondangerdisplaygapgridloosepaddingremstacktightvar
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.
Step 2 of 3 in Custom properties, step 6 of 21 in Responsive & modern CSS.