loading...
Cover image for CSS Variables Quick Reference

CSS Variables Quick Reference

connoro7 profile image Connor Dillon ・3 min read

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:

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

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

: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:

: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:

/* 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:

<p>
    <!-- BLUE TEXT -->
</p>

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

CSS Variables & Media Queries:

@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:

@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:

.modal {
    --base: 8;
    margin: calc( var(--base) * 1px );
    padding: calc( var(--base) + 6px );
}

Using Variables for Building Themes

: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

@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.

.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.

<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.

// 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;

Posted on by:

connoro7 profile

Connor Dillon

@connoro7

Flannel and coffee enthusiast living the cliché software developer life in Seattle, WA. Huge fan of other people's dogs, music production, and fitness.

Discussion

markdown guide