Getting Started with CSS Variables
Did you know that instead of having static values, you can use variables to make your styles dynamic?
Enter CSS Variables or, as they're formally known, CSS Custom Properties.
In this article, we'll introduce you to this powerful feature that can make theming and styling your sites much more flexible.
What are CSS Variables?
CSS Variables allow you to store a value under a custom name and then reference that name throughout your stylesheet. Instead of repeatedly typing out values (like a color code or a font size), you can store them in a variable.
If you want to change the value later, you update the variable, and all references will automatically adjust!
Declaring a CSS Variable
You declare CSS Variables inside a selector. The most common approach is to declare them inside the :root
selector, which makes them globally available.
:root { --primary-color: #3498db; }
In this example, --primary-color
is the variable name and #3498db
is its value.
Using a CSS Variable
To use a CSS Variable, you reference it with the var()
function:
button { background-color: var(--primary-color); }
Now, every button will have a background color of #3498db
.
Why Use CSS Variables?
Theming: Imagine a site with a light and dark mode. With CSS Variables, you can easily switch between themes by just updating a few variables.
Maintainability: No more scrolling through thousands of lines to change a repeated value. Update a variable, and the change is applied everywhere.
Dynamic Styles with JavaScript: Want your site's styles to change based on user input? With JavaScript, you can adjust CSS Variables on the fly, and they will auto-magically update everywhere.
Basic Theming with CSS Variables
Here's a simple example of how you might use CSS Variables for theming:
:root { --primary-color: #3498db; --secondary-color: #2ecc71; } body[data-theme="dark"] { --primary-color: #34495e; --secondary-color: #27ae60; } button { background-color: var(--primary-color); border-color: var(--secondary-color); }
By changing the data-theme
attribute on the body, we can dynamically adjust our theme!
Start small, play around with them, and soon you'll realize just how powerful (and fun!) they can be.
Happy coding! 🚨