Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 21, 2023 06:36 pm GMT

Dark Mode Toggle

I have always been intrigued 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' allow 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

Fist, 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 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 he 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)


Original Link: https://dev.to/mihir_chhatre/dark-mode-toggle--4m0b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To