Changing the same spacing value in dozens of CSS rules is tedious. A CSS variable, also called a custom property, gives that value a double-hyphen name. Define it once, usually on :root for global use, then reuse it with var(). Changing the definition updates every place that uses it. section 3.3
One value, several uses
Define :root { --base-spacing: 8px; } and use .card { padding: var(--base-spacing); }. The same pattern works for colors and font sizes. A shared value can also participate in a calculation, rather than being copied into each rule. section 3.3
Variables are especially useful with calc(), but substitution does not make invalid arithmetic valid. For example, margin-left: calc(100% - var(--unit)) works when --unit is 2rem. For multiplication, keep one value unitless: font-size: calc(var(--scale) * 1rem) works when --scale is 1.5; multiplying two lengths does not. section 3.3.2
Allow for a missing value
Use font-size: calc(var(--heading-size, 2rem) + 0.5rem) to supply 2rem when --heading-size is unavailable. Without a fallback, a missing variable makes the whole property invalid. section 3.3.3
Listing 8.4 A modular scale based on the golden ratio (1.618)
<head>
<style>
:root {
--ratio: 1.618; #1
--base: 1.25rem; #2
--step-1: calc(var(--base) / var(--ratio)); #3
--step-2: calc(var(--step-1) / var(--ratio)); #4
--step1: calc(var(--base) * var(--ratio)); #4
--step2: calc(var(--step1) * var(--ratio)); #4
--step3: calc(var(--step2) * var(--ratio)); #4
}
h1 { font-size: var(--step3); }
h2 { font-size: var(--step2); }
h3 { font-size: var(--step1); }
p { font-size: var(--base); }
h4 { font-size: var(--step-1); }
h5 { font-size: var(--step-2); }
</style>
</head>
<body>
<h1>Golden ratio scale</h1>
<h2>Golden ratio scale</h2>
<h3>Golden ratio scale</h3>
<p>Golden ratio scale</p>
<h4>Golden ratio scale</h4>
<h5>Golden ratio scale</h5>
</body>
A modular type scale stores a base size and ratio, then derives heading and smaller text sizes through successive calc() expressions. Change the base or ratio to adjust the related sizes together. section 8.3.3 section 8.5
Variables can also hold theme colors. Define background and text colors on :root, then redefine those properties inside a prefers-color-scheme: dark media query to switch modes. section 7.5.5



