# CSS Custom Properties using Var() function

# Why is it needed?

If you have been following web development for some time you would the hype around CSS Custom Properties. So let’s see Why So Hype ??( *read in Heath Ledger Joker tone* 😜)  

We all are habituated to writing CSS and specifying properties for elements. However many times to maintain a similarity across the website we tend to write repetitive code. One of the major goals for developers is to reduce this repetitive code enabling easy, fast ways to change properties and enable efficient code writing and code debugging, and code refactoring.

This is where CSS Variables come into play . Take a look at the code below and see the amount of repetition used in the CSS file.

```css
.list1 {
  color: white;
  background-color: darkviolet;
  margin: 2rem;
  width: 50px;
  height: 50px;
  display: block;
}

.list2 {
  color: white;
  background-color: darkblue;
  margin: 2rem;
  width: 150px;
  height: 70px;
  display: block;
}
.list3 {
  color: white;
  background-color: darkviolet;
  margin: 2rem;
  width: 75px;
}
.txt1 {
  background-color: darkviolet;
}
```

---

<aside>
💡 As we see for applying the same `color` to different classes we had written the code each time. Note the repetitive CSS. The `background-color` is set to `darkviolet`.

</aside>

Here is a Codepen Example with HTML and CSS to show the code.

[https://codepen.io/aashirwad01/pen/XWzgKzN](https://codepen.io/aashirwad01/pen/XWzgKzN)

## Solution: So What to do?

To avoid such a need for repetition we can define properties using CSS variables to write once and use throughout the code.

This also enables us to change property once and update throughout the doc without having to change it all.

*Thus facilitating easy debugging and refactoring of code alongside way less repetition.*

> CSS variables or also known as Custom CSS properties are values defined by the author to use throughout a document.
> 

They are set using custom property notation (e.g. `—main- color : black`) and are accessed using var() function (e.g. `color : var( —main-color);`)

This might not look a big deal in small code however big websites and in complex code, we might use the same `color` in hundreds of places requiring global search and update for changing a simple `color`  😪.

Custom properties allow us to store ( not such a good term to use we will see why later 😬) and reference in multiple places 😎.

# How to use it?

In order to define any custom property we begin, its name with a `double hyphen`(`—`). and valid CSS property value. Just like any other CSS property, it is written within double brackets { } i.e a rule set.

```css
:root {
  --main-bg-color: darkviolet;
}

element {
  --text-color: white;
}
```

You might have noticed`:root` in the above code. It is a pseudo-class that allows us to define properties within it that can be used globally across entire HTML.

You can learn about `:root` from below MDN doc.

[:root - CSS: Cascading Style Sheets | MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/:root)

# Using it in Code

**Enough Chitchat! Let’s start using it in Code** 😋

So take an example of the above defined code .Pasting here again for reference.

```css
.list1 {
  color: white;
  background-color: darkviolet;
  margin: 2rem;
  width: 50px;
  height: 50px;
  display: block;
}

.list2 {
  color: white;
  background-color: darkblue;
  margin: 2rem;
  width: 150px;
  height: 70px;
  display: block;
}
.list3 {
  color: white;
  background-color: darkviolet;
  margin: 2rem;
  width: 75px;
}
.txt1 {
  background-color: darkviolet;
}
```

<aside>
💡 Let’s Change it using CSS Custom Properties 🤩

</aside>

Here we declare a custom property of `—main-bg-color` in `root` and use it wherever required in code. Pretty Dope 😏

The result is the same, yet this is very useful for refactoring the style of the site at once.

```css
:root{
  --main-bg-color:darkviolet;
}

.list1 {
  color: white;
  background-color: var(--main-bg-color);
  margin: 2rem;
  width: 50px;
  height: 50px;
  display: block;
}

.list2 {
  color: white;
  background-color: darkblue;
  margin: 2rem;
  width: 150px;
  height: 70px;
  display: block;
}
.list3 {
  color: white;
  background-color: var(--main-bg-color);
  margin: 2rem;
  width: 75px;
}
.txt1 {
  background-color: var(--main-bg-color);
}
```

## Let me share a secret tip 🤫

<aside>
💡 It is not necessary to define custom properties only within a `:root` pseudo class . Defining it in`:root` allows us to change properties globally. However, if we want to only change property locally for an element-specific even this can be done by specifying the custom properties only within the scope of the ruleset.

</aside>

To see and use `Var()` in CSS here is the above code’s codepen snippet.

[https://codepen.io/aashirwad01/pen/ZEayBew](https://codepen.io/aashirwad01/pen/ZEayBew)

# Splitting Colors using Custom Properties 😳

**This is one of the coolest use of custom properties 😎** 

Say we can define different values for hsl in custom variables and we can use combinations of them together or can change the `color` value individually in specific cases.

[https://codepen.io/aashirwad01/pen/vYWZxgw](https://codepen.io/aashirwad01/pen/vYWZxgw)

<aside>
💡 See how we can control the hsl while hovering without having to write the entire code for background again.

By breaking into parts we can control elements and can change style based on user interaction without using JS. 🥳

</aside>

***Here is an article to see how individual values in elements can be changed in CSS.***

[https://css-tricks.com/now-css-custom-properties-thing-value-parts-can-changed-individually/](https://css-tricks.com/now-css-custom-properties-thing-value-parts-can-changed-individually/)

## How to use Calc() with Custom properties 💪

Here is small sample code to see how to use `calc()` with `var()` function .

```css
.d2{
  
  --spacing: 1.2rem;
  padding: calc(var(--spacing) / 2));
  
  
 
}
```

# Custom property fallbacks

Say we have declared a custom property, what will happen if we don’t provide any value to the variable set 🤔

The callback will use the second comma-separated value instead 😏

For e.g

```css
html {
  font-family: var(--fonts, Helvetica, Arial, sans-serif);
}
```

Here if `—fonts` doesn’t have any value specified font family takes additional fallback values 🤩

We can also have a series of fallbacks, but for that we need them to be nested.

Take this example :

```css
html {
  font-family: var(--fonts, var(--fontsfallback,Arial);
}
```

*Pretty Cool* 😁

# Now, What will happen if the wrong value is given to Custom Property? 🥲

Whenever a invalid substitution in `var()` is used , either the initial value or the inherited value is used . 

Let’s see the below code 

```html
<p class="para">Because Var() is the hero CSS deserves, 
but not the one it knows right now </p>
```

### Let’s look at the CSS code ( wherein lies the mis step 😶)

```css
:root { --text-color: 2rem; }

.para{
  color:var(--text-color);
  
}
```

See how we have written `2rem` for `—text-color` property . So the resulting `.para` has a default `color` set for it which is `black`! 

Since there is no parent from which `.para` could inherit any `color`, the initial `color` which is default is used instead of the inherited one.

![Untitled](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ed476f47-9d2e-481d-ab6c-7be1b9a92508/Untitled.png)

### *On that note let’s see Inheritance of Custom Properties 🤗*

# Inheritance of Custom Properties

For reference here is the codepen snippet below.

Below is a short description of how divs are arranged.

We have a div 1 with `class d1` within which we have 

- div 2 with `class d2`
    - Inside div 2 we have div 3 with `class d3` and div 4 with `class d4`
    

[https://codepen.io/aashirwad01/pen/rNYwWjR](https://codepen.io/aashirwad01/pen/rNYwWjR)

In the above case, we have property `spacing` to define `padding spacing` in `class d2` and `padding spacing` and `margin spacing` in `class d3`.

We observe that :

- In Class `d2` padding spacing is `1.2rem`. Specified using local custom property spacing
- In Class `d3` padding spacing is `2rem` and margin-bottom is also `2rem`. Specified using local custom property spacing.
- In Class `d4` padding spacing is `1.2rem` ( inherited from class `d2`).

## Gotcha! Does var “store” values? 🤔

<aside>
💡 It should be kept in mind that var() does not “store” values, unlike actual variables. Value is computed wherever needed and not stored.

</aside>

# Future of CSS

We have seen how using the `var()` function we create a CSS Variable which gets substituted for the value of the Custom Property it refers to.

There is a suggestion for “**Higher Level Custom Properties**”.

Custom Properties that control a number of other CSS Properties. As per the proposal right now we have a new `@if` at-rule and alongside `var()` this would make custom properties **Kaboom 💥💥.**

Also, **Atomic CSS** is also in trend and hype these are immutable classes that have complete responsibility of applying a unit style to the selected component of the UI.

**In Short and Crisp way Future of CSS is not** ****Just Monstrous “ it’s Ahead Of The Curve “****😉

### *(Comment on how you used `Var()` and specifically comment on How many of my Batman Movie dialogues you Got 😉 )*
