Building a Type Scale with Custom Properties
You'll learn how to use CSS custom properties (variables) to create and maintain a consistent type scale across your entire website.
In the previous lesson, you learned the theory behind type scales—mathematical relationships that create visual harmony between heading and body text sizes. Now it's time to implement that system in a way that's reusable and easy to adjust.
Why Custom Properties Are Perfect for Type Scales
CSS custom properties (those variables that start with --) are ideal for defining your type scale because you can:
- Define all font sizes in one central location
- Update the entire scale by changing a single base value
- Maintain consistency across hundreds of pages
- Make global adjustments without searching through your entire stylesheet
Think of it like a musical instrument: you tune the strings once (set your variables), and every note you play (every element you style) stays in harmony.
Building Your Scale
First, establish your base size and ratio as custom properties in your :root:
:root {
--base-size: 1rem;
--ratio: 1.25; /* Major third scale */
/* Define your scale steps */
--text-xs: calc(var(--base-size) / var(--ratio));
--text-sm: var(--base-size);
--text-md: calc(var(--base-size) * var(--ratio));
--text-lg: calc(var(--base-size) * var(--ratio) * var(--ratio));
--text-xl: calc(var(--base-size) * var(--ratio) * var(--ratio) * var(--ratio));
}
Now apply them semantically:
body { font-size: var(--text-sm); }
h4 { font-size: var(--text-md); }
h3 { font-size: var(--text-lg); }
h2 { font-size: var(--text-xl); }
Want to experiment with a different ratio? Change one number in :root and your entire typographic system adjusts proportionally.
Key Takeaway: Custom properties let you encode your entire type scale as reusable variables, making it trivial to maintain consistency and experiment with different ratios across your design system.