What is a CSS Variable and How to Use It
CSS variable is a custom property that stores a value you can reuse throughout your CSS code. It helps keep styles consistent and easy to update by defining values once and referencing them with var().How It Works
Think of a CSS variable like a label on a jar in your kitchen. Instead of writing the full recipe every time, you just grab the jar labeled "sugar". Similarly, a CSS variable stores a value, like a color or size, under a name you choose.
You define a CSS variable inside a selector using --variable-name, and then use it anywhere with var(--variable-name). This means if you want to change the color or size later, you only update the variable once, and all places using it update automatically.
Example
This example shows how to define a CSS variable for a color and use it to style text and a button background.
:root {
--main-color: #3498db;
}
body {
color: var(--main-color);
font-family: Arial, sans-serif;
}
button {
background-color: var(--main-color);
border: none;
color: white;
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
}
button:hover {
background-color: #2980b9;
}When to Use
Use CSS variables when you want to keep your styles consistent and easy to update. For example, if your website uses the same brand colors or font sizes in many places, defining them as variables saves time and reduces mistakes.
They are also great for theming, like switching between light and dark modes, because you can change variable values dynamically without rewriting all styles.
Key Points
- CSS variables start with
--and are accessed withvar(). - They make your CSS easier to maintain and update.
- Variables can be scoped globally or locally inside selectors.
- They support dynamic changes with JavaScript for interactive designs.