Dark mode makes websites easier on the eyes and gives a modern feel. Here’s how to add a dark mode toggle using CSS variables and a bit of JavaScript.
- HTML
<!DOCTYPE html>
Dark Mode Toggle
Toggle Dark Mode
This is some text to see the color change.
- CSS `:root { --bg-color: #ffffff; --text-color: #000000; }
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
body.dark-mode {
--bg-color: #121212;
--text-color: #e0e0e0;
}`
3.JAVASCRIPT
`const toggle = document.getElementById("theme-toggle");
toggle.addEventListener("click", () => {
document.body.classList.toggle("dark-mode");
});
`
Quick Explanation of this Code:
CSS Variables (--bg-color, --text-color) define theme colors.
JavaScript toggles the dark-mode class on the
when the button is clicked.When dark-mode is active, CSS overrides the variables to switch to dark theme colors.
Top comments (0)