Adding Dark Mode to HTML
One of the most useful, often taken for granted, features in mobile and web applications is dark mode. Besides making the user interface look better, it could also provide some health benefits for users. So how can you add a dark mode toggle to your HTML page? It is easy with setting some CSS and JavaScript.
1. CSS
Inside your HTML page, add the following CSS code. This defines a CSS class selector where the CSS is looking for a style class that we defined with a name dark. We're going to change the background to (nearly) pure black and text color to (nearly) pure white.
/* Dark mode */
.dark{
background-color: #222;
color: #e6e6e6;
}
2. JavaScript
While inside of your HTML page, add the following JavaScript code. This snippet will use a browser API to detect the whether your local system is using light or dark mode. If your local system is using dark mode, the HTML page will activate a function named ToggleDarkMode(). ToggleDarkMode() will add the CSS class selector to the HTML document's body element.
let isDarkMode= window.matchMedia('(prefers-color-scheme: dark)').matches;
if(isDarkMode){
console.log('Currently in dark mode');
ToggleDarkMode();
}
else{
console.log('Currently not in dark mode');
}
function ToggleDarkMode() {
var element = document.body;
element.classList.toggle("dark");
}
3. Toggle Button
Some users may prefer to see what your website looks like with the opposite setting, so having a toggle would be great. Simply add the following button within your HTML document. The button will use the onclick property to run the ToggleDarkMode() function, which enables dark mode on your HTML's body element.
<button onclick="ToggleDarkMode()">Toggle</button>
Found any other ways to enable dark mode in HTML? Let us know in the comments below, or contact us in our blog
Top comments (0)