What are CSS Variables?
Tags: css, webdev, beginners
Published: 2022-01-06 01:27:08

CSS variables, also known as custom properties(official name) or cascading variables, are a useful CSS feature that allows you to set a value once and reference it many times throughout an HTML document. As with other programming languages, variables are a valuable tool that helps reduce redundant tasks and hold values that can be used or changed later. CSS variables were introduced in 2016 with the release of Chrome 49, and are now supported across all modern web browsers with the exception of Internet Explorer.

## Why use CSS Variables?
It will make writing and maintaining your CSS easier. Most websites have a color palette that is repeated throughout. Now imagine you have a website and want to change the color palette. In a complex website you'd have to update the colors in the many places it's used. That is a tedious task that no one wants to do. With CSS variables you'd only have to update the colors in once. It doesn't just have to be colors either, any CSS style that is repeated can take advantage of this. Not only that but variables make your CSS easier to read. It's much easier to understand CSS that has descriptive variable names than one with values set individually.

## How to use CSS Variables
Setting a variable is just like setting a CSS property. The only difference is you use a custom variable name which must be prefixed with double hyphens (--). Note that CSS variables are case sensitive meaning `--main` is not the same as `--MAIN`.
```css
--name: value
```
To reference a variable use the `var()` function.
```css
var(--name, fallback)
```
Here `name` is the variable name and `fallback` is an optional value that will be used if the variable is invalid. The `var()` function only accepts two arguments. Anything following the first comma is taken as the fallback value. However you can still define multiple fallback values.
```css
var(--name, red, black)
```
Here `red, black` is the second argument and will be used just the same as if you were to just define red as the value and black as the first fallback. If you decide to used another variable as a fallback you cannot do the following:
```css
var(--name, --fallback-var)
```
This would be invalid as `--fallback-var` would be used and has no value when used outside the first argument of the `var()` function. Instead you would need to do the following:
```css
var(--name, var(--fallback-var))
```
This is a valid way to define a variable as a fallback to another variable, but be warned as this can cause performance issues as it takes more time to parse variables. 

If a variable name is invalid with no fallback the property will be set to the default value or inherited value. This may cause styling issues that make your page less accessible or difficult to parse. For example you may have a dark mode and a variable for the font color. If that variable is invalid the font color will default to black(or the inherited value). Now the text is going to be very difficult or impossible to read. While most modern browsers support CSS variables, there are users that may access your page from Internet Explorer or an older browser. There's also human error, you don't want a typo to break the styling of your page. For these reasons it's good practice to include a fallback.

CSS variables are typically set in the `:root` pseudo-class as it gives the variable a global scope and thus can be used throughout the document. If you need to you can set a variable anywhere in the document but it will only be accessible within that element's local scope.

Here's a short example of how you might use CSS variables:
```css
:root {
  --heading-color: red;
  --paragraph-color: indigo;
}
h1 {
  color: var(--heading-color);
}
p {
  color: var(--paragraph-color);
}
#highlight {
  color: var(--heading-color);
}
```
Here the variables `--heading-color` and `--paragraph-color` are set under the `:root` selector which gives them a global scope. The `--heading-color` variable is then used as the color value for the `h1` selector and the `highlight` id, and the `--paragraph-color` is used as the color value for the `p` selector.

## CSS Variables in JavaScript
Yes, you can get and set CSS variables in JavaScript. To get a variable value use the `.getPropertyValue()` method. To set a variable value use the `.setProperty()` method.
```js
// get root element
let root = document.querySelector(':root');

// get my-var value
root.style.getPropertyValue('--my-var');

// set my-var value to green
root.style.setProperty('--my-var', 'green');
```

## Common Use Cases

I won't go into too much detail on these, but here are a few common use cases for CSS variables.

### Theming
If you want different themes for your website, such as dark/light mode, you can use a set of variables that you change for each theme. The following is a simple example of how you could implement a dark/light mode feature with CSS and JavaScript. 
```css
:root {
  --bg-color: white;
  --text-color: black;
}
.dark-mode {
  --bg-color: black;
  --text-color: white;
}
```

```js
const darkModeSwith = document.querySelector('#switch');

darkModeSwith.addEventListener("click", function () {
  document.body.classList.toggle("dark-mode");
});
```

### Media Queries
Responsiveness is important in the current world of web development and variables with media queries makes this much easier to achieve. You could do the following and the margin size will change when the screen width is less than 600px.

```css
:root {
  --margin: 25px;
}
@media screen and (min-width: 600px) {
  :root {
    --margin: 100px;
  }
}
```

### Size and Space Elements Relative to Each Other
You can use the `calc()` function along with CSS variables to easily set things relative to each other. If you wanted to make your heading twice the size of your paragraph font you could do the following.
```css
:root {
  --paragraph-font: 14px;
}
h1 {
  font-size: calc(var(--paragraph-font) * 2);
}
```
## More CSS variables
Interested in learning more about CSS variables? Check out the following pages I used for reference:
[Mozilla Web Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties)
[Google Developers](https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care)
[Lambda Test](https://www.lambdatest.com/blog/guide-to-css-variables-with-examples/)
[CSS Docs](https://devdocs.io/css/using_css_custom_properties)