Skip to main content
Practice

What are CSS Variables?

CSS Variables are a feature in CSS for storing and reusing values across your stylesheet. These variables usually start with a -- prefix.

For example, if you have a particular color that is used repeatedly throughout your website, you can store this color value in a variable and use that variable whenever you want to reference it.


How to Use

  1. Declaring Variables: Variables are typically declared in the :root or within a specific selector.
CSS
:root {
--main-color: #ff4500;
}

In the code above, the variable --main-color is storing the color value #ff4500.

  1. Using Variables: The stored variable value can be used with the var() function.
CSS
h1 {
color: var(--main-color);
}

The code above sets the color of all h1 tags to the value stored in the --main-color variable, which is #ff4500.


Advantages

  1. Reusability: Once a value is assigned to a variable, it can be easily used throughout multiple places in a website.

  2. Maintainability: If a design change requires a different color, you only need to change the variable's value once. This change will automatically apply to all places where the variable is used.

  3. Adaptability: CSS Variables can be integrated with JavaScript, making it useful to dynamically change styles.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.