CSS Variables


CSS Variables, also known as CSS Custom Properties, allow you to store values in one place and reuse them throughout your stylesheet. They make CSS more flexible, easier to maintain, and much more powerful, especially in large projects. Instead of repeating the same colors, font sizes, or spacing values again and again, you can define them once and use them wherever needed.

In this chapter, you will learn what CSS variables are, why they are important, how to define and use them, their scope, inheritance behavior, real-world use cases, and best practices for writing clean and scalable CSS.

What Are CSS Variables

CSS variables are custom properties that hold reusable values. They are defined using a special syntax that starts with two hyphens and are accessed using the var() function.

Example:

:root {
    --main-color: blue;
}

Here, --main-color is a CSS variable that stores the value blue.

To use it:

p {
    color: var(--main-color);
}

This makes the paragraph text blue using the variable value.

Why CSS Variables Are Important

Before CSS variables, developers had to repeat values everywhere or rely on preprocessors like Sass. CSS variables solve this problem directly in native CSS.

CSS variables help you:

  • Maintain consistent design values

  • Update styles quickly from one place

  • Reduce repeated code

  • Build scalable and modular CSS

  • Create themes like dark mode and light mode

  • Improve readability of stylesheets

In real projects, CSS variables significantly reduce maintenance effort.

Difference Between CSS Variables and Normal CSS Values

Normal CSS values are fixed and cannot be reused dynamically.

Example without variables:

h1 {
    color: #3498db;
}

p {
    color: #3498db;
}

If you want to change the color, you must update it everywhere.

Using CSS variables:

:root {
    --primary-color: #3498db;
}

h1 {
    color: var(--primary-color);
}

p {
    color: var(--primary-color);
}

Now, changing the color in one place updates it everywhere.

How to Declare CSS Variables

CSS variables are declared inside a selector using the --variable-name syntax.

Example:

.container {
    --box-padding: 20px;
}

Variables can be declared inside:

  • :root

  • Any HTML element

  • Classes

  • IDs

The location where a variable is declared affects its scope.

What Is :root in CSS Variables

The :root selector represents the highest-level element in the document, usually the <html> element.

Variables defined in :root are globally accessible.

Example:

:root {
    --font-main: Arial, sans-serif;
    --spacing: 16px;
}

These variables can be used anywhere in the stylesheet.

Using :root is the most common and recommended way to define global CSS variables.

How to Use CSS Variables with var()

The var() function retrieves the value of a CSS variable.

Syntax:

var(--variable-name)

Example:

button {
    padding: var(--spacing);
    font-family: var(--font-main);
}

This makes the button follow the global spacing and font values.

Fallback Values in CSS Variables

CSS variables support fallback values. If a variable is not defined, the fallback value is used.

Example:

p {
    color: var(--text-color, black);
}

If --text-color is not available, the text color becomes black.

Fallbacks make CSS safer and more predictable.

Scope of CSS Variables

CSS variables follow normal CSS scoping rules.

Variables declared inside an element are only available to that element and its children.

Example:

.card {
    --card-bg: lightgray;
}

.card p {
    background-color: var(--card-bg);
}

The variable --card-bg is available inside .card but not outside it.

This allows component-level customization.

Inheritance Behavior of CSS Variables

CSS variables are inherited by default.

If a variable is defined on a parent element, child elements can access it.

Example:

section {
    --text-size: 18px;
}

section p {
    font-size: var(--text-size);
}

This inheritance behavior makes variables very powerful for nested layouts.

Overriding CSS Variables

CSS variables can be overridden in specific contexts.

Example:

:root {
    --theme-color: blue;
}

.dark-theme {
    --theme-color: white;
}

Usage:

body {
    color: var(--theme-color);
}

When .dark-theme is applied, the color changes automatically.

This is the foundation of theming systems.

Using CSS Variables for Colors

One of the most common uses of CSS variables is color management.

Example:

:root {
    --primary: #1abc9c;
    --secondary: #2c3e50;
    --background: #f5f5f5;
}

Using them:

body {
    background-color: var(--background);
    color: var(--secondary);
}

This ensures color consistency across the entire website.

Using CSS Variables for Spacing

Spacing values like margin and padding are often repeated.

Example:

:root {
    --space-small: 8px;
    --space-medium: 16px;
    --space-large: 24px;
}

Usage:

.card {
    padding: var(--space-medium);
    margin-bottom: var(--space-large);
}

This creates a consistent spacing system.

Using CSS Variables for Typography

Font sizes, line heights, and font families are ideal for variables.

Example:

:root {
    --font-base: 16px;
    --font-large: 24px;
}

Usage:

body {
    font-size: var(--font-base);
}

h1 {
    font-size: var(--font-large);
}

This improves readability and scalability.

CSS Variables and JavaScript

CSS variables can be updated dynamically using JavaScript.

Example:

document.documentElement.style.setProperty('--primary-color', 'red');

This allows real-time theme changes, animations, and user-driven customization.

CSS variables bridge the gap between CSS and JavaScript.

CSS Variables vs Preprocessor Variables

CSS preprocessors like Sass also support variables, but they work differently.

Key differences:

  • CSS variables work at runtime

  • Sass variables are compiled at build time

  • CSS variables can change dynamically

  • Sass variables cannot be updated in the browser

Modern CSS often uses CSS variables even without preprocessors.

Common Mistakes with CSS Variables

Some common errors include:

  • Forgetting to use var()

  • Declaring variables in the wrong scope

  • Overusing variables for single-use values

  • Not providing fallback values

Understanding scope and inheritance prevents most issues.

Best Practices for CSS Variables

Follow these best practices for clean CSS:

  • Define global variables in :root

  • Use meaningful variable names

  • Group related variables together

  • Use variables for colors, spacing, and fonts

  • Avoid unnecessary variables

Well-structured variables make CSS easier to manage.

Real-World Use of CSS Variables

In real projects, CSS variables are used for:

  • Design systems

  • Theme switching

  • Component libraries

  • Responsive layouts

  • Dark mode support

They are a core part of modern CSS architecture.

Summary of CSS Variables

CSS variables provide a powerful way to create reusable, flexible, and maintainable styles. By storing values in custom properties and reusing them with var(), you can manage colors, spacing, typography, and themes efficiently. Understanding scope, inheritance, and best practices allows you to write cleaner CSS and build scalable designs. Mastering CSS variables is essential for modern, professional web development.


Practice Questions

Q1. Create a variable for primary color and apply it to headings.

Q2. Define a --radius and use it for button border-radius.

Q3. Use --font-base for font size of all paragraphs.

Q4. Add --box-shadow for cards and apply it.

Q5. Define a fallback for an undefined variable.

Q6. Set --container-width and use it in a .container class.

Q7. Change --main-color dynamically using JavaScript.

Q8. Create light and dark themes using CSS variables.

Q9. Apply --gap between grid columns.

Q10. Make a reusable --transition-speed variable and apply it to links.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top