Themeing with CSS3 Variables and localStorage

CSS3 variables has easily become one of my new favorite features added to CSS. Combining this with HTML5's custom data attributes, we can define entire themes with ease with just a few CSS variables.

What once would have taken an incredible amount of CSS and and JS, we can now do with a CSS and a simple attribute on the body tag.

In addition to themeing, this is useful for responsiveness, and makes organizing our CSS a breeze.

Below we can see two variables defined for an example theme of light/dark, and then setting that variables for the body class.

body[data-theme="light"] {
    --bg-color: white;
}
body[data-theme="dark"] {
    --bg-color: #292828;
}
body {
    background-color: --bg-color;
}

This is an example of how CSS variables are also extremely useful for responsiveness, allowing us to adjust font sizes, spacing on elements, adjusting our header height - just to name a few options.

html {
    --base-font-size: 18px;
    --logo-font-size: 70px;
}

// Make  things smaller for mobile
@media screen and (max-width: 650px) {
    html {
        --base-font-size: 17px;
        --logo-font-size: 60px;
    }
    body {
        --space: 1.5rem;
        --header-height: 60px;
    }
}