Dark mode & Light mode

Basic tutorial using CSS, HTML and JS to create Dark and Light mode in your page .

Note :

Don’t forget to import yours CSS file and JS file inside the HTM file.

  1. HTML Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Toggler</title>
<body>
<header>
<div id="toggleBtn" class="toggler">
<div id="toggleDisplay" class="toggle toggleFalse"></div>
</div>
</header>
<div>
<h1>Hello</h1>
</div>
<script src="./app.js"></script>
</body>
</html>

2. CSS Code :

header{

display: flex;
justify-content: flex-end;
align-items: center;
min-height: 50px;
height: 10vh;
background-color: black;

}
body{
margin: 0;

}
.darkMode {
color: white;
background-color: black;
}
.lightMode{color: black;
background-color: white;
}
.toggler{height: 30px;
width: 60px;
background-color: grey;
border-radius:25px;
margin-right: 10px;
}
.toggle{height: 30px;
width:30px;
background-color: aliceblue;
border-radius: 100%;
transition: margin-left 0.5s ease;
}
.toggleTrue{margin-left: 30px;
}
.toggleFalse{
margin-left: 0;
}

3. JS Code :

var toggleDisplay = document.querySelector("#toggleDisplay");
var toggleBtn = document.querySelector("#toggleBtn");
var bodyTage = document.querySelector("body");
var toggleStatus;
toggleBtn.addEventListener("click", function () {toggleStatus = toggleDisplay.getAttribute("class");if (toggleStatus === "toggle toggleFalse") {toggleDisplay.setAttribute("class", " toggle toggleTrue");
document.body.setAttribute("class", "darkMode");
// bodyTage.setAttribute("class", "darkMode");
} else {toggleDisplay.setAttribute("class", "toggle toggleFalse");
// bodyTage.setAttribute("class", "ligthMode");
document.body.setAttribute("class", "lightMode");
}});

Conclusion :

Very short and basic tutorial how to implement dark and light mode in your project . I hope you will add it to your future projects !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store