Implement Dark Mode On Your Website.
Matthew Marquise
Posted on February 25, 2021
Dark Mode is an extremely popular feature to implement into your website using basic HTML, CSS and JS. So why don't you have it on yours yet? In three easy steps you can enhance your site to incorporate dark mode! Let's get started.
Table Of Contents
Step 1
Step 1
Step 3
Demo On CodePen
Step 1:
If you don't already have a website, simply create an HTML file.
<!-- index.html -->
<!DOCTYPE html>
<head>
<title>Dark Mode Feature</title>
<meta charset="UTF-8">
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
...
<body>
</html>
Once you have that lets implement the HTML and CSS
Step 2:
In the basic HTML form lets now input everything we will need. Start by connecting your JS and CSS file. add
<!-- index.html -->
<!DOCTYPE html>
<head>
<title>Dark Mode Feature</title>
<meta charset="UTF-8">
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- ADD CSS FILE -->
<link rel="stylesheet" href="main.css">
<!-- ADD JS FILE -->
<script src="main.js"></script>
</head>
<body>
...
<body>
</html>
Now we need to create those two files. Feel free to change the name of your css and
In the CSS file we'll add these lines of code.
/* main.css */
body {
background-color: white;
color: black;
}
.dark-mode {
background-color: black;
color: white;
}
Within the body we have specified that we want our default background to be white with black text. Then in the dark-mode class we've specified that we want want to change the background to black with white text.
Now we need to create the main.js file, the brain of our dark mode feature.
//main.js
function darkmode() {
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !wasDarkmode);
const element = document.body;
element.classList.toggle('dark-mode', !wasDarkmode);
}
function onload() {
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
Once you've successfully created both the main.css and main.js files there's one last thing.
Step 3:
Though you may think you're done, you aren't. Ask yourself this very question. What if my website has multiple pages? how will each page stay in dark mode without returning to the default white background? The answer is far simpler than you think. In the initial body tag on each page add:
onload="onload()"
That's it. Hope this was helpful! Thanks for reading!
Demo On CodePen
Posted on February 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.