Creating a toggle button for dark and light mode is easy with our guide for beginner web developers. Learn how to implement it using HTML, CSS, and jQuery.
Table of Contents
Before tackling this topic, I would like to tell you why a dark mode is necessary on your website. Dark mode became popular in the last 3-5 years as companies started rolling out these modes to benefit night users and those with bright screens. You know, dark mode is everywhere on iOS, Android, Windows. If it's everywhere, that doesn't mean you should have one, so why does it matter. let's say if a user visits your website at night to read an article, lighter colors will strain the user's eyes. so I think the dark mode is an essential feature for every website.
Here are the benefits of using a dark theme:
- Improve text readability
- Better Contrast
- Reduce eye strain
- Less flickering
- Less blue light
- Less likely to cause photophobia
- Can save a small amount of electricity
A dark/light mode switch allows website visitors to choose between a dark and light theme for the website. In this tutorial, we'll guide you through the process of creating a dark/light mode switch for your website using HTML, CSS, and jQuery. Not only is a dark/light mode switch a popular design trend, but it also provides users with a better browsing experience, especially when browsing at night or in low-light environments.
Join My Telegram Channel to Download the Project: Click Here
Prerequisites:
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, I'm going to provide you with a simple markup element that you can style however you like.
Our demo also uses jQuery. In this example, we'll add the script to the HTML file directly from the Cloudflare CDN so it's always up to date. Be careful to add the jQuery library before the custom script so it can use its functionality.
After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.
Here's a breakdown of the HTML code:
Document Type and HTML Tag:
<!DOCTYPE html> <html lang="en">
<!DOCTYPE html>
: Declares the document type and version of HTML.<html lang="en">
: The root element with the language attribute set to English.
Head Section:
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dark Mode</title> <link rel="stylesheet" href="styles.css"> </head>
<meta charset="UTF-8">
: Sets the character encoding to UTF-8.<meta name="viewport" content="width=device-width, initial-scale=1.0">
: Ensures the page is responsive by setting the viewport width to the device width.<meta http-equiv="X-UA-Compatible" content="ie=edge">
: Ensures compatibility with Internet Explorer's rendering engine.<title>
Dark Mode</title>
: Sets the title of the webpage.<link rel="stylesheet" href="styles.css">
: Links an external CSS file for styling the webpage.
Dark Mode Switch:
<div class="switch">Dark mode: <span class="inner-switch">OFF</span> </div>
<div class="switch">
: A container for the dark mode toggle.<span class="inner-switch">
OFF</span>
: A span to indicate the current state of the switch (OFF).
Title:
<h1 class="title">Animals</h1>
<h1 class="title">
Animals</h1>
: The main heading for the page.
Article:
<article> <h1>Tiger</h1> <p><small>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Tenetur, laudantium.</small></p> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eius, nulla. Debitis qui quam, ratione totam voluptatibus vitae necessitatibus sit laudantium, optio quis nam quidem est officia nemo architecto cum repellendus dolores eveniet ullam eligendi porro?</p> <img src="Tiger.jpg" alt="Tiger Image"> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Praesentium tempora error deleniti eum facilis eaque neque laboriosam repellat molestiae deserunt, aliquid numquam a, nisi qui ipsa debitis obcaecati, voluptate expedita veritatis similique laudantium. Magni dolorum dolores labore eius aut. Fugiat.</p> </article>
<article>
: Contains the main content of the page.<h1>
Tiger</h1>
: Heading for the article.<p>
<small>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Tenetur, laudantium.</small>
</p>
: A small introductory paragraph.<p>
: Paragraphs with sample text about tigers.<img src="Tiger.jpg" alt="Tiger Image">
: An image of a tiger with alternative text.
Scripts:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="script.js"></script>
<script src="https://cdnjs.cloudflare.c...n.js">
</script>
: Links to the jQuery library.<script src="script.js">
</script>
: Links to an external JavaScript file for additional functionality (e.g., toggling dark mode).
This is the basic structure of our dark/light mode switch using HTML, and now we can move on to styling it using CSS.
Step 2 (CSS Code):
Once the basic HTML structure of the website is in place, the next step is to add styling to the website using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.
Next, create the CSS for the light mode and dark mode. The CSS below uses a column-based flexbox layout that allows you to easily position elements on the page, especially the .switch class that handles the dark mode toggle wrapper and img elements. Create a CSS file with the name of styles.css and paste the given codes in your CSS file.
Here's a detailed breakdown of what each part of the code does:
General Styles
body { font-family: sans-serif; font-size: 1.125rem; display: flex; flex-direction: column; max-width: 50rem; margin: 0 auto; padding: 0 0.9375rem; }
- font-family: sans-serif;: Sets the font family of the text to a sans-serif type.
- font-size: 1.125rem;: Sets the font size to 1.125 times the root element's font size.
- display: flex;: Makes the body a flex container.
- flex-direction: column;: Arranges the child elements in a column.
- max-width: 50rem;: Sets the maximum width of the body to 50 rem units.
- margin: 0 auto;: Centers the body horizontally within its parent.
- padding: 0 0.9375rem;: Adds padding of 0.9375 rem units on the left and right sides of the body.
Small Text Style
small { font-style: italic; }
- font-style: italic;: Makes the text in small elements italic.
Article Styles
article { display: flex; flex-direction: column; }
- display: flex;: Makes the article a flex container.
- flex-direction: column;: Arranges the child elements in a column.
Image Styles
img { max-width: 100%; display: block; align-self: center; }
- max-width: 100%;: Ensures the image does not exceed the width of its container.
- display: block;: Makes the image a block-level element.
- align-self: center;: Centers the image horizontally within its flex container.
Switch Styles
.switch { align-self: flex-end; margin: 0.9375rem; }
- align-self: flex-end;: Aligns the switch to the end of the flex container.
- margin: 0.9375rem;: Adds a margin of 0.9375 rem units around the switch.
Inner Switch Styles
.inner-switch { display: inline-block; cursor: pointer; border: 1px solid #555; border-radius: 1.25rem; width: 3.125rem; text-align: center; font-size: 1rem; padding: 0.1875rem; margin-left: 0.3125rem; }
- display: inline-block;: Makes the inner switch an inline block element.
- cursor: pointer;: Changes the cursor to a pointer when hovering over the inner switch.
- border: 1px solid #555;: Adds a border of 1 pixel with a solid color of #555.
- border-radius: 1.25rem;: Rounds the corners of the inner switch with a radius of 1.25 rem units.
- width: 3.125rem;: Sets the width of the inner switch to 3.125 rem units.
- text-align: center;: Centers the text inside the inner switch.
- font-size: 1rem;: Sets the font size to 1 rem unit.
- padding: 0.1875rem;: Adds padding of 0.1875 rem units inside the inner switch.
- margin-left: 0.3125rem;: Adds a left margin of 0.3125 rem units.
Dark Mode Styles
.dark, .dark * { background-color: #222; color: #e6e6e6; border-color: #e6e6e6; }
- background-color: #222;: Sets the background color to a dark shade (#222).
- color: #e6e6e6;: Sets the text color to a light shade (#e6e6e6).
- border-color: #e6e6e6;: Sets the border color to a light shade (#e6e6e6).
body {
font-family: sans-serif;
font-size: 1.125rem;
display: flex;
flex-direction: column;
max-width: 50rem;
margin: 0 auto;
padding: 0 0.9375rem;
}
small {
font-style: italic;
}
article {
display: flex;
flex-direction: column;
}
img {
max-width: 100%;
display: block;
align-self: center;
}
.switch {
align-self: flex-end;
margin: 0.9375rem;
}
.inner-switch {
display: inline-block;
cursor: pointer;
border: 1px solid #555;
border-radius: 1.25rem;
width: 3.125rem;
text-align: center;
font-size: 1rem;
padding: 0.1875rem;
margin-left: 0.3125rem;
}
.dark,
.dark * {
background-color: #222;
color: #e6e6e6;
border-color: #e6e6e6;
}
Step 3 (JavaScript Code):
Finally, the script.js file adds toggle functionality to the toggle button. So when the user clicks the toggle button, the dark mode will be applied and the label on the button will change to "ON". And, if the user clicks the toggle when the page is in dark mode, the light mode will be applied and the label will change to "OFF".
Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.
$( ".inner-switch" ).on("click", function() {
if( $( "body" ).hasClass( "dark" )) {
$( "body" ).removeClass( "dark" );
$( ".inner-switch" ).text( "OFF" );
} else {
$( "body" ).addClass( "dark" );
$( ".inner-switch" ).text( "ON" );
}
});
Final Output:
Conclusion:
Congratulations, you've now learned how to create a dark/light mode switch using HTML, CSS, and jQuery. Not only does this switch make your website look more modern and stylish, but it also provides a better user experience for visitors. By following the steps outlined in this tutorial, you can easily implement this switch on your own website and make it more user-friendly for everyone.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊