DEV Community

loading...
Cover image for CSS Variables Quick Reference

CSS Variables Quick Reference

Connor Dillon
Full-stack Javascript developer, fire dancer, physics nerd, Vim fanboy, and technical writer! I'm passionate about my work and love to talk shop, so say hi!
・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 */
}
Enter fullscreen mode Exit fullscreen mode

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. */
}
Enter fullscreen mode Exit fullscreen mode

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

:root {
    --text-color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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" */
}
Enter fullscreen mode Exit fullscreen mode

Which then gives us:

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

<section class=“card”>
    <!-- RED TEXT -->
</section>
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Using Media Query to Toggle Light and Dark Mode:

@media (prefers-color-scheme: dark) {
    :root {
        --text-color: white;
        --background: black;
    }
}
Enter fullscreen mode Exit fullscreen mode

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 );
}
Enter fullscreen mode Exit fullscreen mode

Using Variables for Building Themes

:root {
    red: 86;
    green: 23;
    blue: 107;
}

.card {
    color: rgb( var(red), var(green), var(blue) )
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode
body {
    color: var(--text-color);
    background: var(--background);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
body {
    color: var(--text-color);
    background: var(--background);
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Discussion (0)