If you have been familiar with CSS for some time, then you know how powerful it is, not just for plane-styling HTML documents.
In this article, I will show you how you can achieve a dark mode toggle feature in your project using just CSS!
BTW this is my first article on dev.to so bear with me for some mistakes which I am surely going to make 😬
Things you need to know:
- HTML
 - CSS
 
Approach
In our project, we will use a checkbox to toggle between light mode and dark mode. We will style the container's background and font color based on a checkbox property to wrap up our entire page content.
HTML
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="style.css" type="text/css">
      <title>Dark Mode Toggle</title>
   </head>
   <body>
      <!-- Checkbox Toggle -->
      <input type="checkbox" id="toggle">
      <!-- Container -->
      <div class="container">
         Make sure to include all your content inside this container div.
      </div>
   </body>
</html>
CSS
Universal & Container Styling
We will start by giving the styling to the universal selector and the container.
/* Universal Styling */
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
/* Container for all the elements */
.container {
  width: 100%;
  min-height: 100vh;
  padding: 10px;
  background-color: #EEE;
  color: #333;
  transition: all 0.4s ease-out;
}
Toggle Button Styling
Now we will turn our checkbox into a toggle button by applying some simple styles.
/* Toggle Button */
#toggle {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  width: 60px;
  height: 30px;
  border-radius: 30px;
  background-color: #333;
  position: absolute;
  top: 50px;
  right: 50px;
  transition: all 0.5s ease-in;
  cursor: pointer;
  z-index: 1;
}
/* Making a dot switch inside the Toggle Button */
#toggle::before {
  content: "";
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #EEE;
  position: absolute;
  top: 50%;
  left: 3px;
  transform: translateY(-50%);
  transition: all 0.5s ease-in;
}
/* Changing toggle button background when checked */
#toggle:checked {
  background: #03FFC0;
}
/* Changing dot switch color and moving to the right side when checked */
#toggle:checked::before {
  background: #333;
  left: 32px;
}
Final Styling
Finally, we will change the container background using this style when the checkbox property is checked.
/* Changing the background & font color when checked */
#toggle:checked ~ .container {
  background-color: #333;
  color: #EEE;
}
That's it! 🤩 You now have the fully working page with the dark mode toggle feature.
See the complete source code here.
Video Tutorial: here.
Thank you for reading! ❤
              
    
Top comments (0)