Home / CSS3 / What are CSS Variables and How to Use CSS Variables?

What are CSS Variables and How to Use CSS Variables?

5 minutes read
158 Views
Blog post thmbnail css variables

CSS variables, also known as CSS custom properties, are similar to variables in other languages in that they allow developers to store data in key-value pairs.

For example:  

--main-color: #006fc0;

You don’t have to remember the color value each time you use CSS in this situation; instead, you use the name ‘–main color.

CSS variables have DOM access, which means you may create variables with a local or global scope, alter them using JavaScript, and change them based on media queries.

The usage of brand colors in online applications is a frequent practice while designing them. Instead of repeatedly copying and pasting the same colours, you may save them as variables and use them in different places.

Overview and History

  • CSS didn’t have native variable support at first, therefore developers turned to CSS Preprocessors like SAAS, which fixed the problem by using preprocessor variables.
  • CSS variables are used in the same way as any other variable in a different language, that is, to assign a value to them and then refer to that value afterwards.
  • Also known as Custom Properties or Cascading Variables. (The value is not actually stored.) (In this blog post, we’ll use them interchangeably.)

What are CSS Variable Scopes and How Do You Define CSS Variables?

In Javascript we usually declare and initialize a variable as follow:

let a = 10;
const b = 20;
var c = 30;

We don’t use let, const, or var in CSS; instead, we use two hyphens (dashes –) before the user-defined variable name and place them in scope.
Yes, just as we have scopes in Javascript such as function scope, block scope, and global scope, we too have scopes in CSS.

:root {
  --main-color: #fcf033;
  --sec-color: blue;
}

We’ve used the:root the selector in this case. It has global scope because it targets the top element of the DOM. Other local scopes based on different CSS Selectors can be created in the same way.

But then there’s the issue of specificity, as in if we have the identical CSS-property specified at the global and local levels, which value will be preferred?

Consider the following example as a code snippet.

See the Pen Blog- CSS Variables 1 (dev.to) by Shivaansh Agarwal (@shiv-1998) on CodePen.

We can see a number of things here:

  • How to get a hold of a CSS- Variable.
  • Local variables have a higher priority than those of global variables.
  • We can utilise the property and then declare it afterwards, and CSS will still take it into account, just as it does with div.

Accessing CSS Variables using var()

body {
  color: var(--main-color);
}

h1,
h2,
h3 {
  color: var(--sec-color);
}

The var() function can be used to access the CSS Variable specified previously, as seen above.

The var() function accepts the property name as an argument, fetches the property’s value from the stylesheet if one exists, and replaces it with the real CSS-Property.
As a result, unlike other languages, CSS variables do not save values; instead, when used, they simply replace them with the real CSS value.

If a property is missing, var() can be used to supply a fallback value.

Composition with CSS variables

Variables in CSS can be used anywhere in a value. Multiple values can be combined in this way.

section {
  background-image: linear-gradient(var(--main-color) 0%, var(--sec-color) 100%);
}

Incorporating CSS Variables into JavaScript

div {
  font-size: var(--main-font-size, 16px);
}

Take a look at the Codepen below to see how to access and alter CSS-Variable in Javascript.

  • Use the calculated CSSStyleDeclaration object’s getPropertyValue() function to get the value of a custom property at runtime.
  • Use the setProperty() function of the CSSStyleDeclaration object to set the value of a custom property during runtime.

See the Pen Blog CSS-Variables 2 by Shivaansh Agarwal (@shiv-1998) on CodePen.

Benefits of CSS Variables usage in your code

Consider the following CSS Code.

:root {
  --main-font-color: #E9E9E9;
  --main-bg-color: rgba(128,128,0,1);
}
p {
  color: var(--main-font-color);
  background-color: var(--main-bg-color);
}
span {
  color: #E9E9E9;
  background-color: rgba(128,128,0,1);
}

Now that we’ve looked at both ways of using CSS, with and without CSS Variables, let’s look at the advantages of utilizing CSS Variables over CSS without them.

Ease of maintainability

Let’s imagine you’ve spent hours selecting appropriate styles and colors, and then the demand for that styling shifts. To alter the colors and styling, you’ll have to go through the entire project, but if you’ve utilized CSS variables, you could update the value of the CSS property once and it would be reflected everywhere.

2- Code becomes more readable

As we can see from the examples above, the variables are user-defined, allowing them to include semantic meaning. As a result, utilising these variables makes more sense because they are easier to comprehend and maintain.

What’s the difference between native CSS variables and preprocessor variables like SAAS?

  • Native CSS Variables can be dynamically updated at runtime, which is one of the primary differences.
  • Inside media-queries, define CSS-Properties. Other differences can be found in the following section, which includes a fantastic essay on CSS-Tricks.

Browser Support

Custom properties are currently supported by Chrome 49, Firefox 42, Safari 9.1, and iOS Safari 9.3.

CSS variables are now supported by 93 percent of users around the world.

Check browser support for  CSS Variables

CSS Variables (Custom Properties)  - browser support chart -CaIUse

Further Reading

Check out the following to learn more:


Post author

A bright, talented, ambitious and self-motivated 💻 Freelancer, ⌨ Programmer, JavaScript and Typescript lover 📍

  Tweet It


Leave a Reply

Your email address will not be published. Required fields are marked *