Adding a dark mode to your website has become a modern standard. It enhances accessibility, improves readability at night, and gives your interface a sleek look.
In this tutorial, you’ll learn how to build a dark mode toggle from scratch using only HTML, CSS, and a little JavaScript — perfect for beginner developers.
👁️ Preview
🧱 Step 1: Basic HTML Setup
We’ll begin with a simple page and a button to toggle the theme.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dark Mode Toggle</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a simple example of dark mode toggle.</p>
<button id="toggle-theme">Toggle Dark Mode</button>
<script src="script.js"></script>
</body>
</html>
🎨 Step 2: Create Light and Dark Theme with CSS
/* Default (Light Mode) */
body {
background-color: #ffffff;
color: #222;
font-family: Arial, sans-serif;
padding: 2rem;
transition: background-color 0.3s ease, color 0.3s ease;
}
button {
padding: 10px 20px;
background-color: #7179F4;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
}
/* Dark Mode */
body.dark-mode {
background-color: #121212;
color: #f1f1f1;
}
body.dark-mode button {
background-color: #525174;
}
✅ We’re toggling a class on <body>
called dark-mode
to switch styles.
⚙️ Step 3: Add JavaScript to Toggle the Theme
Now let’s make the button actually switch between light and dark modes.
const toggleButton = document.getElementById('toggle-theme');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});
✅ Explanation:
- We select the toggle button by ID.
- When clicked, we add or remove the
dark-mode
class from the<body>
. - The transition is smooth thanks to
transition
in CSS.
💡 Optional: Save Theme in Local Storage
Want the site to remember the user’s theme next time they visit?
// Check saved preference
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
}
// Toggle and save
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
const mode = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
localStorage.setItem('theme', mode);
});
✅ Final Result
You now have a simple and modern dark mode toggle that:
- Works with plain HTML, CSS, and JS
- Looks smooth and clean
- Remembers the user’s preference
This is great for personal websites, portfolios, or any UI needing theme switching.
🧩 Bonus Tips
- You can change images, logos, or icons based on the theme
- Use
prefers-color-scheme: dark
in CSS for automatic detection - Combine with a switch button (see our Switch Button Tutorial if you’ve created one!)