Using CSS Variables

If you’re coming from the world of preprocessors, you must be used to using a variable by just referencing its name. With native css variables, things are a little different.

Once a variable has been defined and assigned a value, you can go ahead and use it within a property value. There’s a bit of a gotcha though.

If you’re coming from the world of preprocessors, you must be used to using a variable by just referencing its name.

For example:


$font-size: 20px

.test {
   font-size: $font-size
}

With native CSS variables, things are a little different. You reference a variable by using the var() function.

With the example above, using CSS Variables will yield this:



:root {
   --font-size: 20px 
   }

.test {
   font-size: var(--font-size)
}

Quite different.

Get hands-on with 1400+ tech skills courses.