Welcome to the Magic of CSS Variables!
Imagine having a magic spell that lets you change colors, fonts, or sizes everywhere on your website with just one tweak. Well, that’s exactly what CSS Variables (a.k.a. Custom Properties) do!
In this guide, we’ll break down how to declare and use CSS Variables like a pro. Get ready to write cleaner, more maintainable, and dynamic CSS!
Declaring CSS Variables
Declaring a CSS Variable is as easy as naming your pet goldfish. You just prefix it with --
and store it inside a selector (usually :root
for global use).
Example:
:root {
--primary-color: #ff5733;
--font-size: 18px;
}
Now, --primary-color
and --font-size
are stored and ready to be used!
Using CSS Variables
Once declared, you can use your variables anywhere in your CSS with var(--variable-name)
.
Example:
body {
background-color: var(--primary-color);
font-size: var(--font-size);
}
Boom! Now your background and font size follow the variables you declared. Update once, and it changes everywhere!
Local vs. Global Variables
Global Variables (Defined in :root
)
:root {
--main-bg: #f0f0f0;
}
Can be used anywhere in your CSS.
Local Variables (Defined Inside a Selector)
div {
--box-shadow: 5px 5px 10px rgba(0,0,0,0.2);
box-shadow: var(--box-shadow);
}
Can only be used inside the div
selector!
Using Fallback Values
What if a variable isn’t defined? No worries! You can provide a fallback value.
Example:
p {
color: var(--text-color, blue);
}
If --text-color
isn’t set, the paragraph will be blue!
Updating Variables with JavaScript
Want dynamic styling? Change CSS Variables on the fly using JavaScript!
Example:
document.documentElement.style.setProperty('--primary-color', '#007bff');
This changes --primary-color
to blue dynamically! Perfect for dark mode toggles.
Best Practices for CSS Variables
- Use
:root
for global settings (easier maintenance). - Name variables logically (
--main-color
, not--a1b2c3
). - Use them for repeated values (colors, sizes, margins, paddings, etc.).
- Keep it DRY (Don't Repeat Yourself – variables help!).
- Test browser support (works in all modern browsers, but not in IE11).
Conclusion: CSS Variables = Less Stress, More Power!
With CSS Variables, you write less code, avoid repetition, and make global styling changes in seconds. So why not start using them today? Go experiment and level up your CSS game!
0 Comments