CSS Variables

Write cleaner, reusable, and maintainable CSS using custom properties.

What are CSS Variables?

CSS Variables, also called CSS Custom Properties, allow you to store values (like colors, sizes, fonts) and reuse them throughout your stylesheet.

  • Reduce repeated values
  • Make CSS easier to maintain
  • Improve readability
  • Support dynamic theming

Real-Life Example: Like saving a phone number once and reusing it instead of writing it everywhere.

Why Use CSS Variables?

Without variables, changing a color or size means updating it everywhere manually. CSS Variables solve this problem.

  • One change updates the entire website
  • Perfect for themes (dark / light mode)
  • Cleaner and more professional CSS

Declaring CSS Variables

CSS variables are usually declared inside the :root selector. This makes them available globally.

Declaring Variables


:root {
    --primary-color: #2563eb;
    --secondary-color: #1e40af;
    --font-size-base: 16px;
    --border-radius: 8px;
}

                

Important: CSS variable names always start with --

Using CSS Variables

To use a variable, use the var() function.

Using Variables in CSS


button {
    background-color: var(--primary-color);
    color: #ffffff;
    font-size: var(--font-size-base);
    border-radius: var(--border-radius);
    padding: 10px 20px;
}

                

Now, if you change --primary-color once, all buttons update automatically.

Local CSS Variables

Variables can also be declared inside specific selectors. These variables apply only to that element and its children.

Local Variable Example


.card {
    --card-bg: #f1f5f9;
    background-color: var(--card-bg);
    padding: 20px;
}

                

Tip: Use local variables for component-specific styles.

Fallback Values

Fallback values are used when a variable is not defined.

Fallback Example


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

                

If --text-color doesn’t exist, CSS uses #333333.

Theming with CSS Variables

CSS Variables make theme switching easy.

Light & Dark Theme Example


:root {
    --bg-color: #ffffff;
    --text-color: #111111;
}

.dark-theme {
    --bg-color: #111111;
    --text-color: #ffffff;
}

body {
    background-color: var(--bg-color);
    color: var(--text-color);
}

                

Real Use Case: Dark mode toggle without rewriting CSS.

Best Practices for CSS Variables

  • Define global variables in :root
  • Use meaningful variable names
  • Avoid overusing local variables
  • Group related variables together

Pro Tip: CSS Variables are the foundation of modern scalable CSS.