Sign Up
Go Pro Sign Up Login

CSS Variables Root vs Body Scoping

Dec 04, 2020

Scott Tolinski

CSS Variables have had a huge impact in the way we write our css on Level Up Tutorials. They allow you to make cascading hierarchies of values to theme an entire site by opening up the ability to make large sweeping changes with just a couple of values. In the Level Up Tutorials course Modern CSS Design Systems we explored the idea of creating a dark mode along with other themes by adding a class to the body updating CSS variables.

For a long time we scoped our entire design system to root like this.

Old Code ☹️

:root {
    --primary: red;
    --bg: var(--primary);
}

We would then override the root styles with:

.dark {
    --primary: green;
}
/* --bg === red still ☹️ */

However, this becomes a cascading issue quickly because the end result is --bg still resolving to the :root scope and being set to the value of 'red' rather the intended 'green'. To fix this, we moved our :root scope variables directly onto the body class. This allows for the theme variables to correctly cascade in our overrides. Check out the new code:

New Code ✅

body {
    --primary: red;
    --bg: var(--primary);
}

.dark {
    --primary: green;
}
/* --bg === green ✅ */
css css variables design systems