Skip to main content

Working with CSS Variables (Live Playground)

CSS Variables, also known as Custom Properties, are a powerful feature that allows you to store and reuse values in your stylesheets. In this tutorial, we'll cover the syntax, usage, and benefits of CSS Variables.

Declaring CSS Variables​

To declare a CSS Variable, you use two hyphens -- followed by the variable name and a colon :.

Example:

CSS
:root {
--primary-color: #4caf50;
--secondary-color: #f44336;
}

Using CSS Variables​

To use a CSS Variable, you reference it with the var() function.

Example:

CSS
body {
background-color: var(--primary-color);
color: var(--secondary-color);
}

Benefits of CSS Variables​

  • Reusability: You can define a value once and use it in multiple places.
  • Maintainability: When you need to update a value, you only have to change it in one place.
  • Dynamic changes: CSS Variables can be updated using JavaScript, allowing for dynamic styling.

Scope and Inheritance​

CSS Variables are scoped and can be inherited. You can declare them at the :root level or inside a specific selector.

Example:

CSS
:root {
--primary-color: #4caf50;
}

button {
--primary-color: #f44336;
background-color: var(--primary-color);
}

.header {
background-color: var(--primary-color);
}

.footer {
background-color: var(--primary-color);
}
Live Playground, Try it Yourself

Conclusion​

In this tutorial, we introduced CSS Variables, their syntax, usage, and benefits. By using CSS Variables, you can write more maintainable and dynamic stylesheets, improving your overall development process.