learn2kode.in

CSS Variables

CSS Variables — also known as Custom Properties — allow you to store reusable values in one place and use them throughout your stylesheet. They make your CSS cleaner, easier to maintain, and more consistent, especially in large projects.

What Are CSS Variables?

CSS variables are values you define once and reuse everywhere. They start with two hyphens (--) and are accessed with the var() function.

Example

:root {
  --main-color: #3498db;
  --font-size: 16px;
}

Then use them like:

h1 {
  color: var(--main-color);
  font-size: var(--font-size);
}

Why Use CSS Variables?

How to Declare CSS Variables

CSS variables are usually defined in the :root selector so they can be accessed globally.

:root {
  --primary: #ff6600;
  --padding: 20px;
}

You can also define variables inside any element:

.card {
  --card-bg: white;
}

Using CSS Variables

button {
  background: var(--primary);
  padding: var(--padding);
}

If a variable is missing, you can define a fallback:

color: var(--text-color, black);

Changing Variables Dynamically

CSS variables can be updated using JavaScript — perfect for theme switching.

document.documentElement.style.setProperty('--primary', '#00cc66');

Dark/Light Mode Example

:root {
  --bg: white;
  --text: black;
}

.dark-mode {
  --bg: black;
  --text: white;
}

body {
  background: var(--bg);
  color: var(--text);
}

Switch theme with JS:

document.body.classList.toggle("dark-mode");

Common Use Cases

Table: CSS Variables Properties

Here is a simple table for your page:

Feature Description
--variable-name Declares a custom property
var(--name) Retrieves the variable value
var(--name, fallback) Uses fallback if variable is not defined
:root Best place to define global variables
JavaScript setProperty() Update variables dynamically