Table of Contents
Implementing dark mode in your Hugo theme can enhance user experience by providing a comfortable viewing option in low-light conditions. This guide will walk you through the process of adding a dark mode toggle and styling your theme accordingly.
Understanding Dark Mode in Hugo
Dark mode is a display setting that uses a dark color palette for the interface, reducing eye strain and conserving battery life on devices with OLED screens. In Hugo, you can implement dark mode by adding custom CSS and JavaScript to toggle themes dynamically.
Steps to Implement Dark Mode
- Adding CSS styles for dark mode
- Creating a toggle button
- Using JavaScript to switch themes
1. Define Dark Mode CSS
Start by adding CSS variables for light and dark themes in your stylesheet. Use a class on the <body> element to switch themes.
Example:
/* Light theme styles */
body {
--background-color: #ffffff;
--text-color: #000000;
}
/* Dark theme styles */
body.dark-mode {
--background-color: #121212;
--text-color: #ffffff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
2. Add a Toggle Button
Insert a button in your header or footer to allow users to toggle dark mode.
Example HTML:
<button id="darkModeToggle">Toggle Dark Mode</button>
3. Implement JavaScript for Switching
Add JavaScript to handle the toggle action, saving user preference in local storage for persistence.
const toggleButton = document.getElementById('darkModeToggle');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
// Save preference
if (document.body.classList.contains('dark-mode')) {
localStorage.setItem('theme', 'dark');
} else {
localStorage.setItem('theme', 'light');
}
});
// Load preference on page load
window.addEventListener('load', () => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
}
});
Final Tips
Test your dark mode implementation across different devices and browsers. Adjust CSS as needed for accessibility and visual consistency. Providing a smooth toggle enhances user satisfaction and accessibility.