0
0
CssConceptBeginner · 3 min read

What is a CSS Variable and How to Use It

A 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.

css
: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;
}
Output
The page text and button background appear in a blue color (#3498db). When hovering over the button, the background changes to a darker blue (#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 with var().
  • 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.

Key Takeaways

CSS variables store reusable values to keep styles consistent and easy to update.
Define variables with --name and use them with var(--name) in your CSS.
They help manage colors, sizes, and themes efficiently across your website.
Changing a variable updates all places that use it automatically.
CSS variables can be scoped globally or locally for flexible styling.