Learning CSS Variables!
Tags: css, webdev, showdev, tips
Published: 2021-02-18 17:35:42

[![promo](//rollercoin.com/static/img/referral/banners/ref_72890.gif) ](https://rollercoin.com/?r=kl3gfn3b)

In CSS, custom properties (also known as variables) are properties that we can declare with any name we want and any value we want, for later use.
 
CSS variables are subject to **cascading**, and **inherit** their value from their **parent**.

It is necessary to emphasize that to **create** variables in css we must follow certain rules so that everything goes well.

To declare custom properties (variables) we use a name starting with **two hyphens (--)**, and a value, which can be any valid CSS value (even some nasty stuff, but that's a bit of a gamble). 

Like any other property, we write it inside a set of style rules, something like this:

```css
selector {
  --back-color: blue;
}
```

Note that the selector we use for the style rules defines the scope in which we can use the custom property (the variable). 

A good common practice is to declare variables in the pseudo-class **:root**, and thus apply them globally to the HTML document:

```css
:root {
  --back-color: blue;
}
```

**NOTE:** We must take into account that the variables are case sensitive, that is to say, that a variable with capital letters is different from a variable with lower case letters:

```css
:root {
  --back-color: blue; ✅
  --BACK-COLOR: green; ✅
}
```

Both are correct and it is up to each one how to use them, but it is really recommended that they are always **lowercase** so that they do not deviate from the normal css properties.

###Using Variables

Although we already have our variables, now we must know how to use them, if you wonder if we just put the name of the variable as any value:

```css
body {
  background-color: --back-color; ❌
}
```

Well you are wrong, to use it you have to make use of the function of **var()** that remembering this can only be used *only* as **value** of a property, and that inside it we call to our variable css, so that the function is in charge to replace our variable by its value.

```css
body {
  background-color: var(--back-color); ✅
}
```

Note that this does not replace the value directly, but helps the browser recognize that this variable is equivalent to a previously given value.

###Fallback for variables

If at the moment of using the function **var()** and we also pass it our css variable, this will give as a result the value of our variable, but what happens if we do this but we never declare our css variable?

The truth is that it will not print anything, but thanks to the **var()** function we can pass another value (separating our variable with a ",") that will be taken in case our variable does not exist 😎.

```css
body {
  background-color: var(--back-color, #0f0); ✅ /* Green (#0f0) if --back-color is not defined */
}
```

Thus, we make sure that our property will always have a value, given that for some reason the variable does not exist (we did not declare it yet, by accident someone deleted it, or simply we do not place the name of the variable correctly, etc).

And it is not only that, we can declare multiple fallbacks to have greater security that our property will always have value. But it is still necessary to respect the order and the way to nest the fallbacks:

```css
.caja-2 {
  background-color: var(--color-base, var(--color-back, pink)); ✅ /* Pink if --color-base and --color-back are not defined */
}

.caja-3 {
  background-color: var(--color-base, --color-back, green); ❌ /* Invalid: "--color-back, green" */
}
```

###Inheritance

CSS variables are **inherited**. 
Which means that if no value is set for a custom property on a given element, the value of its parent element is used. 

Let's look at the following HTML:

```html
<div class="parent">
  <div class="son-1">
    <div class="grandson-1"></div>
    <div class="grandson-2"></div>
  </div>
  <div class="son-2">
    <div class="grandson-3"></div>
    <div class="grandson-4"></div>
  </div>
</div>
```

and we have this css:

```css
.son-1 {
  --test: 10px;
}

.grandson-1 {
  --test: 2em;
}
```

In this case, the results of var(--test) are:

* For the element class="son-1": 10px.
* For the element class="grandson-1": 2em
* For the element class="grandson-2": 10px (inherited from its parent [.son])
* For element class="parent": is an invalid value, which is the default value of any custom property.

Note that these are **custom css variables**, they are not real variables as we can find in other programming languages. 

The value is calculated where needed, i.e. only in the element where it is declared and for its children (descendants) and is not stored for use in other rules (for parent or sibling elements).

For example, you cannot declare a css variable for an element and expect to use it in the properties of the descendant (child) of a sibling element. 

The css variable is only set for the matching selector and its descendants, like any normal CSS.

```css
.son-1 {
  --color-background: red; /* we declare the variable */
}

.grandson-1 {
  background-color: var(--color-background); ✅ 
  /* the ".grandson-1" can use the variable since it is a descendant of ".son-1" and therefore can inherit the variable */
}

.grandson-4 {
  background-color: var(--color-background); ❌ 
  /* the ".grandson-4" **NOT** can use the variable since it is a descendant of ".son-2", which is a sibling of ".son-1" and it does not know what variables exist in its siblings and therefore **NOT** can inherit the variable */
}
```

The easiest way for everyone to recognize the variable is to raise it to a level where it can be inherited to all descendants (children), in this example, we can place the variable up to ".parent":

```css
.parent {
  --color-background: red; /* we raise the variable */
}

.son-1 {
  /* --color-background: red; */
  /* we remove the variable */ 
}

.grandson-1 {
  background-color: var(--color-background); ✅ 
  /* the ".grandson-1" can use the variable since it is a descendant of ".parent" and therefore can inherit the variable */
}

.grandson-4 {
  background-color: var(--color-background); ✅ 
  /* the ".grandson-4" can use the variable since it is a descendant of ".parent" and therefore can inherit the variable */
}
```




<center>
If you liked the content you can support me in:
</center>

[![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/G2G42SCZF)

<center>
Want to earn free Bitcoins and Dogecoins? Click on the banner!
</center>

[![promo](//rollercoin.com/static/img/referral/banners/ref_72890.gif) ](https://rollercoin.com/?r=kl3gfn3b)