How to Create and Use CSS Variables
In this blog, we’ll explore what CSS variables are, why they are essential for modern web development, and how they improve maintainability, performance, and flexibility
What Are CSS Variables?
CSS variables, also known as custom properties, allow you to define reusable values in CSS. They are declared using the -- prefix and accessed using the var() function.
Why Are CSS Variables Needed?
- Reusability – Helps avoid repeating values, making CSS cleaner.
- Maintainability – Changing a value in one place updates it across the stylesheet.
- Dynamic Theming – Enables easy light/dark mode and other theme variations.
- JavaScript Interactivity – Can be updated using JavaScript for dynamic styling.
- Performance Improvement – Reduces redundancy, making stylesheets smaller and more efficient.
How to Use CSS Variables?
1. Declaring and Using Variables
:root { --primary-color: #3498db; --font-size: 16px; } body { background-color: var(--primary-color); font-size: var(--font-size); }
Variables are typically defined inside :root so they apply globally.
var(--variable-name) is used to apply the value.
2. Overriding CSS Variables
CSS variables can be overridden in specific elements.
.button { --button-bg: green; background-color: var(--button-bg); color: white; padding: 10px 20px; } .button-danger { --button-bg: red; }
The .button-danger class will have a red background while the default button remains green.
3. Using CSS Variables with JavaScript
You can dynamically change CSS variables using JavaScript.
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
This changes the --primary-color to red dynamically.
4. Creating a Dark Mode Toggle
:root { --bg-color: white; --text-color: black; } .dark-mode { --bg-color: black; --text-color: white; } body { background-color: var(--bg-color); color: var(--text-color); }
document.body.classList.toggle('dark-mode');
This allows toggling between light and dark mode using a simple class switch.
Why CSS Variables Are Better Than Preprocessors (SASS/LESS) Variables
Feature | CSS Variables | SASS/LESS Variables |
---|---|---|
Scope | Can be used dynamically within elements | Only available at compile-time |
JavaScript Control | Can be updated in real-time | Cannot be changed in runtime |
Performance | Faster since it reduces redundant CSS | More CSS is generated on compilation |
Browser Support | Modern browsers support it well | Needs pre-processing |
CSS variables are essential for scalability, maintainability, and performance in modern web development. They help in creating consistent themes, reducing redundancy, and enabling dynamic styling via JavaScript.