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.
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.
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.
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!