CSS Variables, also called CSS Custom Properties, make web design easier and more efficient by allowing you to store reusable values. This guide clearly explains how you can use CSS variables in your projects to create flexible and maintainable designs.
What are CSS Variables?
CSS variables store values (colors, fonts, spacing) that you can reuse across your CSS stylesheets. This makes it simple to maintain and update your design consistently.
Why Use CSS Variables?
- Easy maintenance: Update one variable to change multiple properties at once.
- Consistent design: Keep colors, spacing, and sizes uniform.
- Enhanced readability and easier to manage large CSS files.
How to Declare and Use CSS Variables
Variables are declared using two dashes (--
) followed by the variable name.
Example: Defining Variables
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--spacing: 20px;
}
:root
makes variables accessible globally throughout your CSS.
Example: Using Variables
Use the var()
function to reference a variable:
.button {
background-color: var(--primary-color);
padding: var(--spacing, 10px); /* 10px as fallback value */
}
Changing Variables with Media Queries (Responsive Design)
Variables help you easily adapt your design for different screen sizes:
:root {
--font-size: 16px;
}
@media (max-width: 768px) {
:root {
--font-size: 14px;
}
}
body {
font-size: var(--font-size);
}
Here, the font size adjusts smoothly based on device width.
Updating Variables Dynamically with JavaScript
CSS variables can be updated dynamically through JavaScript:
CSS:
:root {
--main-bg-color: white;
}
body {
background-color: var(--main-bg-color);
}
JavaScript:
document.documentElement.style.setProperty('--main-bg-color', 'lightblue');
Practical Example: Dark Mode with CSS Variables
Easily create a toggleable dark mode:
CSS:
:root {
--bg-color: white;
--text-color: black;
}
.dark-mode {
--bg-color: black;
--text-color: white;
}
body {
background-color: var(--main-bg-color, white);
color: var(--text-color, black);
}
JavaScript (for toggle):
document.querySelector('#toggle').addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});
Advantages of Using CSS Variables
- Easy Maintenance: Update one variable instead of multiple lines of code.
- Dynamic Styling: Easily change designs based on interactions or conditions.
- Cleaner Code: Reduces repetition and improves maintainability.
Best Practices for CSS Variables
- Define variables in
:root
for global usage. - Always provide fallback values to ensure compatibility.
- Group variables logically (colors, spacing, fonts).
Conclusion
CSS variables simplify styling by storing reusable values, making it easier to update and maintain your styles. Whether it’s responsive design, theming, or interactive features, CSS variables are a powerful addition to your toolkit.