C

CSS Tutorial

Clean • Professional

CSS Variables Fonts

2 minute

CSS Variables Fonts

What Are CSS Variables?

CSS Variables, also known as custom properties, are a powerful feature that allows developers to store values (like colors, font sizes, spacing units) in reusable variables. This makes your stylesheets cleaner, more maintainable, and flexible.

Instead of repeating the same values everywhere in your CSS, you can define them once as variables and reuse them wherever needed. If you want to change a color or spacing later, you just update the variable in one place — and it reflects across your whole website.

Why Use CSS Variables?

  1. Consistency in Design – Keep colors, fonts, and spacing uniform across all elements.
  2. Easy Maintenance – Change one variable value and update your entire site instantly.
  3. Dynamic Styling – Variables can be updated using JavaScript or media queries for responsive designs.
  4. Improved Readability – Instead of long hex codes or repeated values, variables make CSS easier to understand.

The var() Function

The var() function is used to insert the value of a CSS variable into your stylesheet.

Syntax :

var(--variable-name, fallback-value)
  • -variable-name → Required. The name of the variable (must start with -).
  • fallback-value → Optional. Used if the variable is not defined.

Example:

color: var(--primary-color, blue);

Global vs Local CSS Variables

  • Global Variables → Declared inside the :root selector (which targets the document’s root). These are accessible throughout the entire CSS file.
  • Local Variables → Declared inside a specific selector, and can only be used within that scope.

Example of Global Variables:

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

Example of Local Variables:

.card {
  --card-bg: #f9f9f9;
  background: var(--card-bg);
}

Example: Using CSS Variables with var()

Without variables (traditional way):

body { background-color: #1e90ff; }
h2 { border-bottom: 2px solid #1e90ff; }
button { background-color: #ffffff; color: #1e90ff; }

With variables:

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body { background-color: var(--blue); }
h2 { border-bottom: 2px solid var(--blue); }
button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
}

Changing Variables with Media Queries

CSS variables can also adapt based on device size:

:root {
  --font-size: 16px;
}

@media (max-width: 600px) {
  :root {
    --font-size: 14px;
  }
}

p {
  font-size: var(--font-size);
}

Changing Variables with JavaScript

Variables are part of the DOM, so you can update them dynamically:

document.documentElement.style.setProperty('--blue', '#6495ed');

 

Article 0 of 0