How to Implement Dark Mode Using CSS and JS (2024)

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>

<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 (1)

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 body

const 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 theme

functionsetTheme(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 (2)

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 theme

functiondetectPreferredTheme() {
// 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.

  • Programming
  • Dark Mode
  • Programming

Your changes have been saved

Email Is sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Manage Your List

Follow

Followed

Follow with Notifications

Follow

Unfollow

Readers like you help support MakeUseOf. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

How to Implement Dark Mode Using CSS and JS (2024)

References

Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5851

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.