How to Use CSS Variables for Fonts: Simple Guide
Use
--variable-name to define a font style inside :root or any selector, then apply it with var(--variable-name) in your CSS properties like font-family or font-size. This lets you reuse and update fonts easily across your site.Syntax
Define a CSS variable with --variable-name inside a selector, usually :root for global use. Use var(--variable-name) to apply the variable value in any CSS property.
- --variable-name: The name of your custom property, starting with two dashes.
- :root: The global scope for CSS variables, so they can be used anywhere.
- var(--variable-name): The function to access the variable's value.
css
:root {
--main-font: 'Arial', sans-serif;
--heading-font-size: 2rem;
}
h1 {
font-family: var(--main-font);
font-size: var(--heading-font-size);
}Example
This example shows how to define font family and font size variables globally, then use them in headings and paragraphs for consistent typography.
css
/* Define font variables globally */ :root { --font-family-base: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; --font-size-base: 1rem; --font-size-heading: 2.5rem; } body { font-family: var(--font-family-base); font-size: var(--font-size-base); margin: 2rem; } h1 { font-family: var(--font-family-base); font-size: var(--font-size-heading); color: #2c3e50; } p { font-size: var(--font-size-base); color: #34495e; }
Output
A page with a large heading in 'Segoe UI' font and paragraphs in the same font but smaller size, all text styled consistently using CSS variables.
Common Pitfalls
Common mistakes when using CSS variables for fonts include:
- Defining variables inside a selector that is not global, limiting their scope.
- Forgetting the
var()function when using the variable. - Using invalid font names or missing quotes for font families with spaces.
- Not providing fallback fonts in the variable value.
Always define font variables in :root for global access and use var(--name) syntax.
css
/* Wrong: variable defined inside a class, not global */ .container { --font-family: 'Comic Sans MS', cursive, sans-serif; } h2 { font-family: var(--font-family); /* This won't work outside .container */ } /* Right: define globally */ :root { --font-family: 'Comic Sans MS', cursive, sans-serif; } h2 { font-family: var(--font-family); }
Quick Reference
- Define variables: Use
:root { --name: value; }for global fonts. - Use variables: Apply with
font-family: var(--name);orfont-size: var(--name);. - Fallbacks: Provide fallback fonts inside the variable value.
- Quotes: Use quotes for font names with spaces.
Key Takeaways
Define font variables globally in :root for easy reuse.
Use var(--variable-name) to apply font family or size in CSS.
Always include fallback fonts and quote font names with spaces.
Avoid defining variables in limited scopes unless intentional.
CSS variables make updating fonts across your site simple and consistent.