CSS Variables Quick Reference
Tags: css, javascript, webdev
Published: 2020-07-30 21:29:53

<!-- TOC -->

- [CSS Variables & Media Queries](#css-variables--media-queries)
    - [CSS Variables and the Calc Function](#css-variables-and-the-calc-function)
    - [Using Variables for Building Themes](#using-variables-for-building-themes)
- [Project: How do you get a user’s preferred color scheme with CSS?](#project-how-do-you-get-a-users-preferred-color-scheme-with-css)
    - [Media Query prefers-color-scheme](#media-query-prefers-color-scheme)
- [Project: Toggle Multiple Themes with CSS Variables](#project-toggle-multiple-themes-with-css-variables)
    - [Toggle CSS Variables](#toggle-css-variables)
- [JavaScript Theme Toggle](#javascript-theme-toggle)

<!-- /TOC -->

#### CSS Variables allow you to reuse values throughout your stylesheets.
- Increases efficiency
- Reduces code duplication

#### Define global variables to be used throughout the entire website:

```css
:root {
    --variable-name: pink; /* can use any valid CSS values */
}
```

#### Put the variable into use with the `var()` function:

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

body {
    color: var(--text-color, pink); /* can provide a “fallback value” if the variable is undefined or invalid. */
}
```

#### To change this value, you only have to update it once in order for it to be applied everywhere:

```css
:root {
    --text-color: yellow;
}
```

Changing the text color to yellow in `:root{ }` will then change the text color in the following elements:

```
p {
    color: var(--text-color);
}

.card {
    color: var(--text-color);
}

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

### Variables cascade downwards, which means you can override them in the children:

```css
/* Global */
:root {
    --text-color: blue; /* global environment inherits "--text-color: blue" */
}

/* Local */
.card {
     --text-color: red; /* anything assigned <class=“card”> will inherit "--text-color: red" */
}
```
Which then gives us:
```html
<p>
    <!-- BLUE TEXT -->
</p>

<section class=“card”>
    <!-- RED TEXT -->
</section>
```

## CSS Variables & Media Queries:
```css
@media screen and (min-width: 600px) {
    :root {
        --margin-base: 10px; //sets default margin size to 10px globally
    }
}

/* Small Screens */
@media screen and (max-width: 600px) {
    :root {
        --margin-base: 6px; //sets default margin size on small screens to 6px
    }
}
```

Using Media Query to Toggle Light and Dark Mode:
```css
@media (prefers-color-scheme: dark) {
    :root {
        --text-color: white;
        --background: black;
    }
}
```

### CSS Variables and the `Calc()` Function
> You can use `calc()` to automatically do the math for you, instead of having to edit each media query separately:
```css
.modal {
    --base: 8;
    margin: calc( var(--base) * 1px );
    padding: calc( var(--base) + 6px );
}
```

### Using Variables for Building Themes
```css
:root {
    —red: 86;
    —green: 23;
    —blue: 107;
}

.card {
    color: rgb( var(—red), var(—green), var(—blue) )
}
```

# Project: How do you get a user’s preferred color scheme with CSS?

### Media Query `prefers-color-scheme`
```css
@media (prefers-color-scheme: dark) {
    :root {
        --text-color: #b6b6b6;
        --background: #ececec;
    }
}

@media (prefers-color-scheme: light) {
    :root {
        --text-color: #1f1f1f;
        --background: #000000;
    }
}
```

```
body {
    color: var(--text-color);
    background: var(--background);
}
```

# Project: How do you toggle multiple themes with CSS variables?

### Toggle CSS Variables

First, define a set of theme values and use them throughout your CSS code.

```css
.dark {
  --text-color: #b6b6b6;
  --background: #ececec;
}

.light {
  --text-color: #1f1f1f;
  --background: #000000;
}

.solar {
  --text-color: #576e75;
  --background: #fdf6e3;
}
```

```
body {
    color: var(--text-color);
    background: var(--background);
}
```
In this example, the theme is attached to the `<body>`, but feel free to use it on any element that is theme-able.

```html
<body class="dark"></body>
```

### JavaScript Theme Toggle

The code below provides map that creates a circular list, so the user can toggle themes in an infinite loop by clicking one button. The user’s preferred theme is stored in the browser’s local storage - this allows it to remain active between browser refreshes or visits from other windows.

```javascript
// Define which theme should load next
const themeMap = {
  dark: 'light',
  light: 'solar',
  solar: 'dark'
};

// Load the existing theme in local storage
const theme = localStorage.getItem('theme');
const bodyClass = document.body.classList;
theme && bodyClass.add(theme);

// Change the theme on a button click
function toggleTheme() {
  const current = localStorage.getItem('theme');
  const next = themeMap[current];


  bodyClass.replace(current, next);
  localStorage.setItem('theme', next);
}

document.getElementById('themeButton').onclick = toggleTheme;
```