0
0
CssHow-ToBeginner · 3 min read

How to Use CSS Variables for Colors: Simple Guide

Use --variable-name to define a CSS variable inside a selector like :root, then use var(--variable-name) to apply the color anywhere in your CSS. This helps keep colors consistent and easy to change across your website.
📐

Syntax

Define a CSS variable by writing --variable-name: value; inside a selector, usually :root for global use. Use the variable by calling var(--variable-name) wherever you want to apply the color.

  • --variable-name: The name you give your color variable, starting with two dashes.
  • value: The color value like #ff0000 or rgb(255, 0, 0).
  • var(): The function to use the variable's value in CSS properties.
css
:root {
  --main-color: #3498db;
}

.element {
  color: var(--main-color);
}
💻

Example

This example shows how to define a blue color variable and use it for text color and background color. Changing the variable in one place updates all uses.

css
:root {
  --primary-color: #1abc9c;
  --background-color: #ecf0f1;
}

body {
  background-color: var(--background-color);
  color: var(--primary-color);
  font-family: Arial, sans-serif;
  padding: 20px;
}

h1 {
  color: var(--primary-color);
}

button {
  background-color: var(--primary-color);
  border: none;
  color: white;
  padding: 10px 20px;
  cursor: pointer;
  font-size: 1rem;
  border-radius: 5px;
}

button:hover {
  background-color: #16a085;
}
Output
A webpage with a light gray background, teal colored text and heading, and a teal button with white text that darkens on hover.
⚠️

Common Pitfalls

Common mistakes include:

  • Not defining the variable before using it, which causes the color to not appear.
  • Forgetting the -- prefix in variable names.
  • Using variables outside their scope if defined inside a specific selector instead of :root.
  • Not using var() function to access the variable.

Always define variables in :root for global access and use var(--name) to apply them.

css
:root {
  --main-color: #ff6347;
}

/* Wrong: missing var() function */
.element1 {
  color: --main-color;
}

/* Correct: using var() */
.element2 {
  color: var(--main-color);
}
📊

Quick Reference

  • Define variable: --name: value; inside :root for global use.
  • Use variable: var(--name) in any CSS property.
  • Change color: Update the variable value once to change all uses.
  • Fallback: Use var(--name, fallback-color) to provide a default color.

Key Takeaways

Define color variables in :root using --variable-name for global access.
Use var(--variable-name) to apply the color anywhere in your CSS.
Changing the variable value updates all places using it, making maintenance easy.
Always include the -- prefix and use var() to access variables correctly.
Use fallback colors in var() to avoid missing colors if a variable is undefined.