What are CSS Variables?
Most programming languages allow you to use variables. Variables are used to store information and manipulated by the program. In CSS, you previously need a preprocessor like SASS or LESS to use variables. CSS Variables are custom properties that you define with specific values and reuse throughout your CSS document.
In CSS as well as programming languages, you can declare your variables either globally or locally. A global variable is a custom property that is available to your entire HTML document. To declare a global custom property, you use the :root pseudo-class.
For example, you want to define your theme colors. You can use the :root pseudo-class to do that.
:root {
--main-color: blue;
--main-text-color: aqua;
}
You can also declare a variable locally. By declaring a custom property locally, you limit the scope or impact that the variable can have.
.primary-background-color {
--background-color: teal;
}
When you create a CSS Variable, you can overwrite the value. By taking advantage of cascade, you can create a new style that changes the default value of a global declare variable.
.text-color {
--main-text-color: orange;
}
Var()
Preprocessors allow you to use a variable by referencing its name. You use the Var() function when inserting the value of a custom property.
.featured-content-box {
background-color: var(--main-color)
}
Calc()
Sometimes you need to do a little math to get your styles to work they way you want them to. Calc() is a native CSS way to do simple math calculations. With it, you can do addition, subtraction, multiplication and division. CSS Tricks talks about use cases for Calc().
For example, you may want to change the width of a style.
.box {
width: calc(100% - 80px);
}
Why use?
CSS Variables can be overwritten, cascade down and used in JavaScript. If you don’t want to use a preprocessor like SASS or LESS, you can use custom variables to make managing your styles a lot simpler.
In Web Dev Simplified’s CSS Variables Tutorial, he gives you a quick introduction on how to use them. You learn what they are, how to write them and use them with JavaScript.
Summary
At first, CSS Variables sounds complicated. They can help you to make your CSS easier to maintain. Variables are a lot easier to use than hex or hsl codes.