TL;DR — CSS variables are custom entities that you can define and reuse in your document instead of repeating the same values.
What's a variable in CSS?
Using variables in CSS not only saves you time but also simplifies updating the page, as you only need to change the value in one place instead of all across the document.
How to create a CSS variable
To define a variable in CSS, you need to write two dashes (
--) in front of its actual name and specify a particular value:
In the example below, we create a custom CSS color variable with a specific color defined in a HEX value:
We recommend using semantic names instead of random ones (e.g.,
--main-text-color is better than
--color1). This will make it easier to read and update the code later.
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
Using variables in CSS code
To reuse the value you specified in the CSS variable, you need to use the
var() function with the variable's name as the value:
CSS variables: useful tips
- When using the
var()function, you can also include a specific value as a fallback. Write it after the variable name and separate the two using a comma.
- Keep in mind that CSS variables are case-sensitive!