What are CSS-Variables?
Tags: css, webdev, cssvariables, cssproperties
Published: 2021-06-26 06:59:28

---
title: What are CSS-Variables?
published: true
description: 
tags: #css #webdev #cssvariables #cssproperties
cover_image: https://images.unsplash.com/photo-1508051123996-69f8caf4891d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1051&q=80
 
---

## Overview and History
1. Initially CSS lacked support for native variables, which led developers turn to CSS Preprocessors like SAAS which solved this problem through the use of preprocessor variables.
2. CSS Variables are used just like any other variable in a different language, i.e. to assign a certain value to then and reference that value later. *(The value is not actually stored )*
3. Also called Custom Properties or Cascading Variables. *(So, we may use them interchangeably in this blog post.)*

## How to Define and Use CSS Variables, & what are Scopes for CSS Variables?
In Javascript we usually declare and intialize a variable in one of the following ways:
```javascript
let a = 10;
const b = 20;
var c = 30;
```
But in CSS, we don't use any such keyword like `let`, `const`, `var`; instead we just use 2 hyphens (dashes --) before the user-defined variable name and put them in a scope.
Yes `scope`, just like in Javascript we've scopes like **function scope**, **block scope**, **global scope** we also have scopes in CSS.
```css
:root {
  --main-color: red;
}
```
Here we've used the `:root` selector. It targets the top element of the DOM and hence has a global scope. Similarly we can have other local scopes based on different CSS Selectors.  
But then the question for specificity arises, like suppose we've the same CSS-property defined at the global level as well as the local level, then which value will be preferred?   
For that consider the following code snippet.
{% codepen https://codepen.io/shiv-1998/pen/qBmWdXE %}
Here we can notice a lot of things:
1. How to access a CSS- Variable.
2. Local variables have higher precedence over global ones.
3. We can use the property and declare it later, and CSS will still consider it, like in case of `div`.

## Accessing CSS Variables using `var()`
As seen above, we can access the CSS Variable defined above using the `var()` function.
`var()` function takes the property name as argument, retrieves it's value from the stylesheet if it's present and replaces it with the actual CSS-Property.
Hence unlike other languages variables in CSS, don't store values, they just replace it with the actual CSS value when used.
* `var()` can also be used to provide a fallback value in case the property is missing.
```css
div {
  font-size: var(--main-font-size, 16px);
}
```

## Using CSS Variables inside Javascript
Consider the following Codepen for understanding how to access and change CSS-Variable in Javascript.
* To get the value of a custom property at runtime, use the `getPropertyValue()` method of the computed CSSStyleDeclaration object.
* To set the value of custom property at runtime, use the `setProperty()` method of the CSSStyleDeclaration object.
{% codepen https://codepen.io/shiv-1998/pen/dyWbYYR %}


## Benefits of using CSS Variables in your code:
Consider the following CSS Code.  
```css
: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, having looked at both the ways of using CSS i.e. with and without the use of CSS Variables, let's see what benefits we get using CSS-Variables over CSS without it.
**1. Ease of maintainability:**
Let's say you've put in hours of work to select appropriate styles and colors and all of a sudden the requirement for that styling changes. You'll have to go through the entire project to change the colors and styling, but suppose if you've used CSS variables, you could've changed the value of the CSS property once and it would reflect at all places.
**2. Code becomes more readable:**
As we can see above, the variables are user-defined so they can contain semantic meaning, and hence using these variables makes more sense as it is becomes much easier to understand and maintiain.

## How are native CSS variables different from Preprocessor variables like SAAS?
1. One of the main difference is Native CSS Variables can be modified at runtime dynamically.  
2. Define CSS-Properties inside `media-queries`.
*For other differences please look at the following section for an amazing article on CSS-Tricks*

## Further Reading:

S.No. | Link
--- | ---
1 | [CSS Variables: Why Should You Care? [Google Developers]](https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care)
2 | [What is the difference between CSS variables and preprocessor variables? [CSS-Tricks]](https://css-tricks.com/difference-between-types-of-css-variables/)
3 | [Using CSS custom properties (variables) [MDN]](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties)