loading...

Intro to CSS Variables

willjohnsonio profile image Will Johnson Updated on ・1 min read

In CSS you can use variables to store information and reference it later in your app using the variable name. This make writing CSS a lot easier because, it cuts down on having to type the same things over and over when you need to make changes in multiple places.

Declaring CSS variables

You can declare a css variable inside of any CSS declaration block {} type --variable-name as the property, then set the value. We'll use red.

body {
    --main-color: red;
}

Using CSS variables

To use a CSS variable you need the var() function. Type var(variable-name) inside of the declaration block you want to use the variable on.

button {
    color: var(--main-color)
}

This is useful because now anywhere you need to change the main-color you change it once and it changes everywhere main-color is referenced. Without CSS variables you would have to go and change each red color manually. 😫

CSS Variable Scope

The CSS selector that you add the variable on, is available for all the children of that element. For example, a variable inside a <div> will be useable by all the elements inside that <div>.

CSS variables are based on CSS specificity and the most specific selector used will be the one that shows in the browser.

For example in this code:

body {
    --main-color: red;
}

header {
    --main-color: blue;
}

Any element that uses main-color outside of header will be red. Any element that uses main-color inside of header will be blue.

Here is example here you can experiment with on codepen

Posted on Feb 4 by:

Discussion

markdown guide
 

Thanks, u just help me to understands CSS variable.