Create a Dark Mode Toggle with HTML, CSS, and JavaScript
In this blog post, we will learn how to create a simple dark mode toggle button using HTML, CSS, and JavaScript. Dark mode is a popular feature that allows users to switch the theme of the website to a darker color scheme. It’s easy to implement and gives your website a modern look!
Step-by-Step Code:
1. HTML Code
<!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="styles.css">
</head>
<body>
<div class="container">
<h1>Dark Mode Toggle Example</h1>
<button id="toggleButton">Toggle Dark Mode</button>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS Code
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
transition: background-color 0.5s ease;
}
.container {
text-align: center;
}
h1 {
color: #333;
transition: color 0.5s ease;
}
button {
padding: 10px 20px;
font-size: 16px;
border: none;
cursor: pointer;
background-color: #4CAF50;
color: white;
transition: background-color 0.5s ease;
}
body.dark-mode {
background-color: #121212;
}
body.dark-mode h1 {
color: white;
}
body.dark-mode button {
background-color: #f1c40f;
color: black;
}
3. JavaScript Code
const toggleButton = document.getElementById('toggleButton');
const body = document.body;
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');
});
Explanation:
Here’s a breakdown of the code:
- HTML: The structure includes a button that toggles the dark mode.
- CSS: Defines both the default light theme and the dark theme using the
dark-modeclass. Smooth transitions are used for background color and text color changes. - JavaScript: A simple script that toggles the
dark-modeclass when the button is clicked, switching between light and dark modes.

