Add a Dark Mode Toggle Using CSS Variables (Step-by-Step Guide)
Introduction
Dark mode has become a popular design trend in modern websites and apps. It’s easy on the eyes, improves battery life on OLED screens, and gives users a choice in how they view content. In this tutorial, you'll learn how to implement a dark mode toggle using CSS variables and JavaScript, step by step.
What Are CSS Variables?
CSS Variables (also called custom properties) let you store reusable values in your CSS. They start with --
and are usually defined inside the :root
selector. For example:
These can be reused like this:
✅ Step-by-Step: Create a Dark Mode Toggle
🧩 Step 1: HTML Setup
We’ll start with a simple HTML file that includes a toggle button.
Explanation:
-
We added a heading, paragraph, and a button to toggle the theme.
-
The button has an
id="toggle-theme"
which we’ll use in JavaScript.
🎨 Step 2: CSS Styling with Variables
Create a style.css
file with the following content:
Explanation:
-
We define default (light mode) values in
:root
. -
When the
body
has the classdark-mode
, the variables change. -
We use
var(--name)
to apply these values throughout the site. -
Transitions are added for a smooth effect.
⚙️ Step 3: JavaScript for Toggle Logic
Create a script.js
file with this code:
Explanation:
-
We grab the toggle button by its ID.
-
On click, we toggle the
dark-mode
class on the<body>
. -
When
dark-mode
is active, the CSS variable values automatically switch.
💡 Bonus Tip: Save Theme Preference (Optional)
Want the site to remember user preference? Update your script.js
like this:
Explanation:
-
We check localStorage for the saved theme on page load.
-
When toggled, we update localStorage to remember the choice.
🧪 Final Output (Preview)
When you click the button, the background, text, and button colors will change based on CSS variables. The transition is smooth, and users can switch modes anytime.
🎯 Why Use CSS Variables for Dark Mode?
-
Cleaner Code: Centralize your color settings.
-
Easier Maintenance: Change theme colors in one place.
-
Dynamic Switching: Use JavaScript to update the class, and variables handle the rest.
✅ Conclusion
Congratulations! 🎉 You’ve successfully created a dark mode toggle using CSS variables and JavaScript. This is a scalable and modern way to offer light/dark themes on your website.
📌 Summary Table
Feature | Description |
---|---|
CSS Variables | Define theme colors using --variable |
JavaScript Toggle | Add or remove dark-mode class |
Smooth Transition | CSS transition for pleasant effect |
Save Preference | Use localStorage to remember theme |