Add Dark Mode in HTML

Detect light or dark mode heyylateef | Jan 20 2022

Dark Mode, Light Mode, Button, Day Switch, Night Switch

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>



About The Lab

Like the content posted on this site? Need help with another web project? Want to give some feedback? Feel free to contact me via email or social media!

Know more!
DigitalOcean Referral Badge