MakeUseOf logo

How to Implement Dark Mode Using CSS and JS

code editor open in dark mode
Image Attribution: Pexels
A front-end developer interested in developing engaging and user-centric products, as well as sharing insight on technical topics through easily comprehensible articles.
Sign in to your MakeUseOf account

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>
 <nav class="navbar">
 <span class="logo">Company Logo</span>
 <ul class="nav__lists">
 <li>About</li>
 <li>Blog</li>
 <li>Contact</li>
 </ul>
 <div id="theme__switcher">
 <img id="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>
 <script src="./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;
}
.navbar span { 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: 5rem auto;
 font-size: 2rem;
 line-height: 2;
 padding: 1rem 2rem;
 border-radius: 10px;
 box-shadow: 2px 3.5px 5px rgba(242, 215, 213, 0.4);
}

At the moment, your interface should look like this:

[画像:Initial UI after HTML and CSS has been applied]
Made by David Jaja -- No attribution required

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
function setTheme(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
function toggleTheme() {
 setTheme(bodyEl.classList.contains("dark") ? "light" : "dark");
}
themeToggle.addEventListener("click", toggleTheme);

This makes your page change themes with a click of the toggle container.

[画像:UI after dark mode has been toggled on]
Made by David Jaja -- No attribution required

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

function setTheme(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);
}
function detectPreferredTheme() {
 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.

AltStyle によって変換されたページ (->オリジナル) /