Comprehending the Objective
I'm focused on grasping the core need: a dark mode toggle button. My thought process is now dissecting its functional requirements. Specifically, it must seamlessly switch themes and, crucially, retain the user's selected preference for future sessions.
Refining the Approach
I'm now detailing the HTML structure. I'll include a container for content and an icon-based button for the toggle. The styling will leverage CSS variables for the light/dark themes and a focus on keeping the button's appearance simple.
Decomposing the Requirements
I've outlined the project: HTML structure with a content container and a toggle button; CSS with variable-based theming; and JavaScript for state management and theme switching. I'm focusing on HTML first, particularly the button. After evaluating toggle switch vs. icon-based button options, I've decided to go with a simple icon button for the cleanest code. I'm sketching out the HTML now, ready to move on.
Evaluating Implementation Details
I'm now refining the JavaScript approach. I've decided to use a dark-mode class on the <body> element for theme toggling. I'll store the theme preference in localStorage to persist across sessions. I'm focusing on the click event handler for the toggle button and the logic to switch between light and dark modes. I'll include system preference checks.
Developing the Implementation Plan
I'm synthesizing the coding strategy, focusing on the core steps: HTML, CSS, and JavaScript. I'm choosing an icon-based button for a cleaner look. I'm now drafting the HTML and CSS, defining CSS variables for light and dark modes, then focusing on the JavaScript, and considering how best to integrate a smooth transition.
Formulating the Implementation
I'm synthesizing the complete solution plan. I've broken down the project into HTML structure, CSS theming, and JavaScript for the switch and storage. I've decided to proceed with an icon-based button for simplicity, and will prioritize keeping the code easy to understand and quick to deploy. I'm focusing on providing the user with well-commented code, which explains the essential steps for achieving the intended behavior.
Here is a complete, copy-paste solution. It uses CSS Variables for easy color management and Local Storage so the browser remembers the user's choice even after they refresh the page.
The Solution
You can save this as a single .html file to test it immediately.
<!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>
<style>
/* 1. CSS VARIABLES (Theming) */
:root {
/* Light Mode Defaults */
--bg-color: #f4f4f4;
--text-color: #333333;
--card-bg: #ffffff;
--btn-bg: #333333;
--btn-text: #ffffff;
--transition-speed: 0.3s;
}
/* Dark Mode Overrides */
body.dark-mode {
--bg-color: #121212;
--text-color: #e0e0e0;
--card-bg: #1e1e1e;
--btn-bg: #ffffff;
--btn-text: #121212;
}
/* 2. GLOBAL STYLES */
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
transition: background-color var(--transition-speed), color var(--transition-speed);
}
/* 3. CONTENT CARD */
.card {
background-color: var(--card-bg);
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
text-align: center;
transition: background-color var(--transition-speed);
max-width: 400px;
}
/* 4. TOGGLE BUTTON STYLES */
#theme-toggle {
background-color: var(--btn-bg);
color: var(--btn-text);
border: none;
padding: 10px 20px;
border-radius: 50px;
font-size: 1rem;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
margin: 20px auto 0;
transition: transform 0.2s;
}
#theme-toggle:active {
transform: scale(0.95);
}
/* SVG styles */
.icon {
width: 20px;
height: 20px;
fill: currentColor; /* Inherits text color */
}
</style>
</head>
<body>
<div class="card">
<h1>Theme Switcher</h1>
<p>Click the button below to toggle between light and dark mode. Your preference is saved automatically.</p>
<button id="theme-toggle" aria-label="Toggle Dark Mode">
<!-- Sun Icon (Shown by default) -->
<svg class="icon sun-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 2.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V3a.75.75 0 01.75-.75zM7.5 12a4.5 4.5 0 114.5 4.5A4.5 4.5 0 017.5 12zM2.25 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5H3a.75.75 0 01-.75-.75zM12 18.75a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0v-2.25a.75.75 0 01.75-.75zM18.75 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5h-2.25a.75.75 0 01-.75-.75zM5.636 5.636a.75.75 0 011.06 0l1.592 1.591a.75.75 0 01-1.061 1.061L5.636 6.697a.75.75 0 010-1.061zM15.192 15.192a.75.75 0 011.061 0l1.591 1.592a.75.75 0 01-1.06 1.06l-1.592-1.591a.75.75 0 010-1.061zM5.636 18.364a.75.75 0 010-1.061l1.591-1.592a.75.75 0 011.061 1.061L6.697 18.364a.75.75 0 01-1.061 0zM16.253 6.697a.75.75 0 011.06-1.061l1.592 1.591a.75.75 0 01-1.061 1.061l-1.591-1.592z"/></svg>
<span id="toggle-text">Light Mode</span>
</button>
</div>
<script>
// 1. Select DOM elements
const toggleButton = document.getElementById('theme-toggle');
const toggleText = document.getElementById('toggle-text');
const body = document.body;
// 2. Define Icons (SVG paths for Sun and Moon)
const sunIconHTML = `<svg class="icon" viewBox="0 0 24 24"><path d="M12 2.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V3a.75.75 0 01.75-.75zM7.5 12a4.5 4.5 0 114.5 4.5A4.5 4.5 0 017.5 12zM2.25 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5H3a.75.75 0 01-.75-.75zM12 18.75a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0v-2.25a.75.75 0 01.75-.75zM18.75 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5h-2.25a.75.75 0 01-.75-.75zM5.636 5.636a.75.75 0 011.06 0l1.592 1.591a.75.75 0 01-1.061 1.061L5.636 6.697a.75.75 0 010-1.061zM15.192 15.192a.75.75 0 011.061 0l1.591 1.592a.75.75 0 01-1.06 1.06l-1.592-1.591a.75.75 0 010-1.061zM5.636 18.364a.75.75 0 010-1.061l1.591-1.592a.75.75 0 011.061 1.061L6.697 18.364a.75.75 0 01-1.061 0zM16.253 6.697a.75.75 0 011.06-1.061l1.592 1.591a.75.75 0 01-1.061 1.061l-1.591-1.592z"/></svg>`;
const moonIconHTML = `<svg class="icon" viewBox="0 0 24 24"><path d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z"/></svg>`;
// 3. Function to update Button UI based on mode
function updateButton(isDark) {
if (isDark) {
toggleButton.innerHTML = `${moonIconHTML} <span id="toggle-text">Dark Mode</span>`;
} else {
toggleButton.innerHTML = `${sunIconHTML} <span id="toggle-text">Light Mode</span>`;
}
}
// 4. Check Local Storage or System Preference on Load
const savedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// Apply saved theme, or default to system preference
if (savedTheme === 'dark' || (!savedTheme && systemPrefersDark)) {
body.classList.add('dark-mode');
updateButton(true);
} else {
updateButton(false);
}
// 5. Handle Button Click
toggleButton.addEventListener('click', () => {
// Toggle class
body.classList.toggle('dark-mode');
// Check current state
const isDarkMode = body.classList.contains('dark-mode');
// Save preference to Local Storage
localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
// Update button UI
updateButton(isDarkMode);
});
</script>
</body>
</html>
Code Breakdown
-
CSS Variables (:root vs body.dark-mode):
- We define colors for
light mode inside :root.
- We define overrides inside
body.dark-mode.
- When JavaScript adds the class
.dark-mode to the body, the brower automatically recalculates the colors because all elements use var(--variable-name).
-
Local Storage (localStorage):
- Reading: On page load, we check
localStorage.getItem('theme').
- Writing: When the button is clicked, we save the current state using
localStorage.setItem('theme', 'dark'/'light'). This ensures that if the user refreshes the page, the theme persists.
-
System Preference (matchMedia):
- The line
window.matchMedia('(prefers-color-scheme: dark)') checks if your computer/phone is already set to Dark Mode.
- The logic prioritizes: 1. Saved Manual Storage → 2. System Preference → 3. Default Light.
-
SVG Icons:
- HTML SVGs are used so they can easily change color using
fill: currentColor. This makes them turn white automatically when the dark theme (and dark button background) is active.