Today I am going to tell you, how to create “Dark & Light Mode Switch With HTML & CSS”.
Here is a demo…
So lets get started…
First start with HTML
<body class="light">
<div class="switch-cont">
<input type="checkbox" id="switch" class="switch"/>
<label for"switch" class="slider">
<i class="fas fa-moon"></i>
<i class="fas fa-sun"></i>
</label>
</div>
</body>
Here I am using “Font Awesome” icons to make it look much better, you can use any other icon library or it is complementary.
Lets add some styling, start with basic body styling
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #fff;
}
Now add some styling to Switch Container or switch-cont
.switch-cont {
position: relative;
display: inline-block;
width: 70px;
height: 40px;
}
Hide the input checkbox, we only need its mechanism
.switch-cont input {
width: 0;
height: 0;
}
Add some styling to the slider
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #28293d;
transition: 0.6s;
border-radius: 100px;
}
.slider:before {
position: absolute;
content: "";
height: 32px;
width: 32px;
left: 4px;
bottom: 4px;
background-color: white;
transition: 0.6s;
border-radius: 100px;
z-index: 2;
}
Increase the font-size of the icons, if you are using icons
.fa-moon {
position: absolute;
font-size: 22px;
top: 9px;
left: 4px;
color: #FEFCD7;
}
.fa-sun {
position: absolute;
font-size: 22px;
top: 9px;
right: 5px;
color: #FFCD02;
}
Time to add some life to code, with the help of checkbox and slider
input:checked + .slider {
background-color: #1c1c27;
}
input:checked + .slider:before {
transform: translateX(30px);
background: #57eba3;
}
.dark {
background: #28293d;
transition: all 0.6s;
}
.light {
background: #fff;
transition: all 0.6s;
}
We are done with CSS, its time for JS. Very simple & efficient code
document.getElementById("switch").addEventListener("change", () => {
document.body.classList.toggle("dark")
document.body.classList.toggle("light")
})
So this is enough for today, lets again meet with some other topic and other code.
Bye Bye :)