Back Home

CSS Variables: Dynamic Styling Made Simple

CSS Custom Properties, commonly known as CSS Variables, are a revolutionary way to manage and reuse values within your stylesheets. They allow you to define a value once and then reference it throughout your CSS, making your code more organized, maintainable, and dynamic.

What are CSS Variables?

Think of them as placeholders for values like colors, font sizes, spacing units, or even complex selectors. They start with two hyphens (--) and can be declared within any CSS selector, but are most commonly defined in the :root pseudo-class to make them globally available.

Declaring and Using Variables

Here's how you declare a variable and then use it:

:root {
  --primary-color: #007bff;
  --base-spacing: 15px;
}

.my-element {
  color: var(--primary-color);
  padding: var(--base-spacing);
  margin-bottom: var(--base-spacing);
  border: 1px solid var(--primary-color);
}

Benefits of Using CSS Variables

Scoping CSS Variables

Variables can be scoped to specific elements or selectors, allowing for more granular control. If a variable is declared on a specific element, it's only accessible to that element and its descendants.

Scoped Variable Example

.theme-dark {
  --text-color: #eee;
  --background-color: #333;
}

.theme-dark p {
  color: var(--text-color);
  background-color: var(--background-color);
  padding: 10px;
}

Live Variable Demo

Experiment with changing CSS variables in real-time. We'll adjust the background color and text color of the box below.

This element's style is controlled by CSS variables.