DEV Community

Cover image for Dark Mode Toggle ↔️
Mihir Chhatre
Mihir Chhatre

Posted on • Edited on

Dark Mode Toggle ↔️

I have always been intrigued by how a simple dark mode can enhance a user interaction experience. To kick off my creative coding journey, I designed the widely used dark-mode toggle.

Let's get building 🏗️

Here's how the toggle would work ->

HTML

An input tag of type 'checkbox' allows switching between modes.

Using the label helps create a view for the toggle. Inside the label, I have used Font Awesome icons to represent the ☀️ and 🌑. The toggle animation and current state representation can be mimicked using a ball within the toggle.

Within the HTML code, it is important to observe how the input and label are linked to produce a check & un-check effect each time the label is clicked.

CSS

First, we need to import Font Awesome to represent the icons. This can be achieved by navigating to the CSS section within the codepen settings. (Simply search 'font awesome' and add it to the external stylesheet.)

The height and width of the body are set to 100vh and 100vw respectively. This essentially means if your screen's dimension is 800*1000, the body will have a dimension of 800*1000 (100% of the screen dimension).

It is important to note that 100% is not the same as using 100vh(or 100vw). An example of one such scenario is shown below -

p is set to 100% height. However, since it is enclosed within a div whose height is 200px, p will have a height of 200px. To ensure that p has the height of the entire body, we can substitute 100% with 100vh to ensure p's height is independent of div's height.

Why use box-sizing?
This property allows us to include the padding and border in an element's total width and height. 'border-box' informs the browser to include any border and padding within the values you specify as the element's dimensions.

The value of the checkbox can be obtained by using the checked pseudo-class. Since we use the adjacent selector('+'), we first target the label, and then the ball.

JavaScript

We target the checkbox and add an event listener to it. Since a checkbox input is used, the change function (adding/removing the 'dark' class to/from the body) is triggered each time the input is checked or unchecked (the mode is toggled).


Voila!
You have a functioning dark mode toggle that you can tweak and reuse! 👏

(P.S Dark Mode >>> Light Mode)

Top comments (0)