DEV Community

loading...
Cover image for CSS Variables

CSS Variables

andrejarrell profile image Andre Jarrell ・2 min read

Intro

CSS variables allow us to reuse common values throughout the document.

CSS variables use custom property notation. They start with two dashes. For example: --main-color

They can be accessed using the var() function: var(--main-color)

🛠 Example

Say we want our site to have a light and dark theme for our users. Nothing better to use than CSS variables! Lets get started!

🎨 CSS

It is good practice to write custom properties in the :root selector so it is available globally!

:root {
    --text: black;
    --background: white;
}
Enter fullscreen mode Exit fullscreen mode

We will use an attribute selector for data-theme to change the color when the theme = dark

[data-theme="dark"] {
    --text: white;
    --background: black;
}
Enter fullscreen mode Exit fullscreen mode

This will set the custom properties for the body tag.

body {
    color: var(--text);
    background: var(--background);
}
Enter fullscreen mode Exit fullscreen mode

⚡ JavaScript

We will grab the body tag to check it's data-theme attribute.

let body = document.querySelector('body');
Enter fullscreen mode Exit fullscreen mode

This toggle function check's the body's data-theme and changes it accordingly.

let toggle = () => {
    let theme = body.getAttribute('data-theme');
    if (theme === 'light') {
        body.setAttribute('data-theme', 'dark');
    } else {
        body.setAttribute('data-theme', 'light');
    }
};
Enter fullscreen mode Exit fullscreen mode

📄 HTML

All we really need for the HTML is the data-theme attribute for the body and a button to envoke toggle().

<body data-theme="light">
    <div class="text-center mt-4">
        <h5>Dark + Light Theme</h5>
        <button type="button" class="btn btn-primary" onclick="toggle()">Toggle</button>
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

👩‍💻 Codepen

Here is the example put to life in Codepen. Check it out!

📚 Resources

🔗 MDN Web Docs
🔗 W3Schools

Discussion (0)

Forem Open with the Forem app