By David Jaja
Dark mode has become a popular preference, so you should look to support it on your sites and in your web apps.
![How to Implement Dark Mode Using CSS and JS (1) How to Implement Dark Mode Using CSS and JS (1)](https://i0.wp.com/static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/09/code-editor-open-in-dark-mode.jpg)
In recent years, dark mode has gained significant popularity as a user interface option. It offers a darker background complemented by lighter text, which not only reduces eye strain but also conserves battery life, especially on OLED screens.
Discover how you can add a dark mode option to your websites and web apps, using a combination of CSS and JavaScript.
Understanding Dark Mode
Dark mode is an alternative color scheme for your website that swaps the traditional light background for a dark one. It makes your pages easier on the eyes, especially in low-light conditions. Dark mode has become a standard feature on many websites and applications due to its user-friendly nature.
Setting Up Your Project
Before you implement this, ensure you have a project set up and ready to work on. You should have your HTML, CSS, and JavaScript files organized in a structured manner.
The HTML Code
Start with the following markup for the content of your page. A visitor will be able to use the theme__switcher element to toggle between dark and light mode.
<body>
<navclass="navbar">
<spanclass="logo">Company Logo</span><ulclass="nav__lists">
<li>About</li>
<li>Blog</li>
<li>Contact</li>
</ul>
See AlsoHow to Enable Dark Mode in Microsoft Edge on Desktop and MobileHow to Modify JS Dialog Box in Odoo 16storybook-dark-mode Addon | Storybook: Frontend workshop for UI development4 dark mode websites to spark ideas for your next web design | Webflow Blog<divid="theme__switcher">
<imgid="theme__image"src="./toggle.svg"alt="" />
</div>
</nav>
<main>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
Odit deserunt sit neque in labore quis quisquam expedita minus
perferendis.
</main>
<scriptsrc="./script.js"></script>
</body>
The CSS Code
Add the following CSS to style the example. This will act as the default light mode which you’ll later augment with new styles for a dark mode view.
@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap");* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html { font-size: 62.5%; }
body { font-family: "Quicksand", sans-serif; }
.navbar {
display: flex;
padding: 2rem;
font-size: 1.6rem;
align-items: center;
color: rgb(176, 58, 46);
background-color: #fdedec;
}
.navbarspan { margin-right: auto; }
.logo { font-weight: 700; }
.nav__lists {
display: flex;
list-style: none;
column-gap: 2rem;
margin: 0 2rem;
}
#theme__switcher { cursor: pointer; }
main {
width: 300px;
margin: 5remauto;
font-size: 2rem;
line-height: 2;
padding: 1rem 2rem;
border-radius: 10px;
box-shadow: 2px 3.5px 5pxrgba(242, 215, 213, 0.4);
}
At the moment, your interface should look like this:
![How to Implement Dark Mode Using CSS and JS (2) How to Implement Dark Mode Using CSS and JS (2)](https://i0.wp.com/static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/09/initial-ui-after-html-and-css-has-been-applied.jpg)
Implementing Dark Mode Using CSS and JavaScript
To implement dark mode, you’ll define its look using CSS. You’ll then use JavaScript to handle the switching between dark and light mode.
Creating the Theme Classes
Use one class for each theme so you can easily switch between the two modes. For a more complete project, you should consider how dark mode may affect every aspect of your design.
.dark {
background: #1f1f1f;
color: #fff;
}.light {
background: #fff;
color: #333;
}
Selecting the Interactive Elements
Add the following JavaScript to your script.js file. The first bit of code simply selects the elements you’ll use to handle the toggle.
// Get a reference to the theme switcher element and the document bodyconst themeToggle = document.getElementById("theme__switcher");
const bodyEl = document.body;
Adding the Toggle Functionality
Next, use the following JavaScript to toggle between the light mode (light) and dark mode (dark) classes. Note that it’s also a good idea to alter the toggle switch to indicate the current mode. This code does so with a CSS filter.
// Function to set the themefunctionsetTheme(theme) {
// If the theme is "dark," add the "dark" class, remove "light" class,
// and adjust filter style
bodyEl.classList.toggle("dark", theme === "dark");
// If the theme is "light," add the "light" class, remove "dark" class,
bodyEl.classList.toggle("light", theme !== "dark");
// adjust filter of the toggle switch
themeToggle.style.filter = theme === "dark" ? "invert(75%)" : "none";
}
// Function to toggle the theme between light and dark
functiontoggleTheme() {
setTheme(bodyEl.classList.contains("dark") ? "light" : "dark");
}
themeToggle.addEventListener("click", toggleTheme);
This makes your page change themes with a click of the toggle container.
![How to Implement Dark Mode Using CSS and JS (3) How to Implement Dark Mode Using CSS and JS (3)](https://i0.wp.com/static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/09/ui-after-dark-mode-has-been-toggled-on-2.jpg)
Enhancing Dark Mode With JavaScript
Consider the following two improvements that can make your dark mode sites more pleasant to use for your visitors.
Detecting User Preferences
This involves checking the user’s system theme before the website loads and adjusting your site to match. Here’s how you can do it using the matchMedia function:
// Function to detect user's preferred themefunctiondetectPreferredTheme() {
// Check if the user prefers a dark color scheme using media queries
const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
setTheme(prefersDarkMode);
}
// Run the function to detect the user's preferred theme
detectPreferredTheme();
Now, any user who visits your site will see a design that matches their device’s current theme.
Persisting User Preference With Local Storage
To enhance the user experience further, use local storage to remember the user’s chosen mode across sessions. This ensures that they don't have to repeatedly select their preferred mode.
functionsetTheme(theme) {
bodyEl.classList.toggle("dark", theme === "dark");
bodyEl.classList.toggle("light", theme !== "dark");themeToggle.style.filter = theme === "dark" ? "invert(75%)" : "none";
// Setting the theme in local storage
localStorage.setItem("theme", theme);
}
// Check if the theme is stored in local storage
const storedTheme = localStorage.getItem("theme");
if (storedTheme) {
setTheme(storedTheme);
}
functiondetectPreferredTheme() {
const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
// Getting the value from local storage
const storedTheme = localStorage.getItem("theme");
setTheme(prefersDarkMode && storedTheme !== "light" ? "dark" : "light");
}
Embracing User-Centric Design
Dark mode goes beyond looks; it's about putting user comfort and preferences first. By following this approach, you can create user-friendly interfaces and encourage repeat visits. As you code and design, prioritize user wellbeing, and deliver a better digital experience for your readers.