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

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)

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

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

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.

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

FAQs

How to Implement Dark Mode Using CSS and JS? ›

Create an HTML document. Add CSS properties to the body and add dark-mode class properties in CSS. Add buttons to switch between Dark and Light Mode. Add functionality to buttons to switch between dark-mode and light-mode using JavaScript.

How to implement dark mode with CSS and JavaScript? ›

Create an HTML document. Add CSS properties to the body and add dark-mode class properties in CSS. Add buttons to switch between Dark and Light Mode. Add functionality to buttons to switch between dark-mode and light-mode using JavaScript.

How do I change my CSS to dark mode? ›

To make a dark theme using CSS variables, start by setting up variables for your colors in the CSS root, like this: ``` :root { --background-color: white; --text-color: black; } ``` Then, make a dark theme by changing these colors: ``` .

How do I render CSS only in dark mode? ›

For example, to supply CSS for dark theme:
  1. @media screen and (prefers-color-scheme: dark) { p { color: #fff; } } And similarly, a light theme:
  2. @media screen and (prefers-color-scheme: light) { p { color: #000; } } ...
  3. p { color: #000; @media screen and (prefers-color-scheme: dark) { color: #fff; } }
May 27, 2022

How to implement dark mode in a website? ›

Steps to Create Dark/Light Mode
  1. Create an HTML Document.
  2. Create CSS for the document file as well as for dark mode.
  3. Add a switch/toggler to toggle between light and dark modes.
  4. Add functionality to the switch/toggler to toggle between light and dark mode using JavaScript or jQuery code.
May 14, 2024

Can you mix CSS and JavaScript? ›

Combining your CSS/JavaScript files into just one CSS/JavaScript file reduces the amount of network requests a browser has to make. That way, the browser finds and downloads everything it needs to render the page much quicker. This is especially useful for websites that use HTTP/1.

How do you add a dark effect in CSS? ›

CSS background-image property allows layering multiple backgrounds. To darken an image, combine a black `linear-gradient` as the front layer and the image as the back layer. Adjust the gradient's opacity to control the darkening effect. Specify the front layer first in the order of `background-image`.

How do I change the color to black in CSS? ›

Use Hexadecimal Values to Change Font Colors

This CSS style can be used to color your paragraphs black because the hex code #000000 translates to black. You could even use shorthand with that hex value and write it as #000 with the same results.

How do I make an entire page black in CSS? ›

The body's size is dynamic, it is only as large as the size of its contents. In the css file you could use: * {background-color: black} // All elements now have a black background. html {background-color: black} // The page now have a black background, all elements remain the same.

What is the color code for dark mode background? ›

material.io advises to use #121212 for dark theme. Twitter's Dim theme uses #FFFFFF text on #15202B background.

How do I force dark mode on all websites? ›

Key Takeaways

Enter "chrome://flags" into Google Chrome's address bar and enable the "Auto Dark Mode for Web Contents" flag to force Google Chrome to display all websites in dark mode. You can also use a browser extension to force sites into dark mode.

Is there a website extension for dark mode? ›

Overview. Dark Night Mode is a Free Open Source Software which makes all the websites you browse into dark/night mode so that you can browse the internet without straining your eyes. It is an extremely useful chrome extension for those who use internet especially at night.

How to make a black background in HTML? ›

The first and simplest way to change the background color is by using inline CSS, which appears in the HTML code itself. To use inline CSS, find the opening tag of the element you want to target, then add the attribute style=“background-color: yourcolorhere;”.

How to integrate JavaScript with CSS? ›

Link your CSS file within the head tag of your HTML with the following code: <link rel="stylesheet" href="box. css"> Link your JS file within the body tag at the very bottom of your code, immediately below the last closing div and above the closing body tag like this: <script src="box. js"></script>

Can you manipulate CSS with JavaScript? ›

It is possible to manipulate CSS styles via JavaScript in a variety of ways. To start with, you can get a list of all the stylesheets attached to a document using Document. stylesheets , which returns an array-like object with CSSStyleSheet objects. You can then add/remove styles as wished.

How to access CSS through JavaScript? ›

The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.

How to add CSS style class in JavaScript? ›

Download Free
  1. Locate or create the element you want to style. Next up, find the HTML element you want to style with a unique CSS class. ...
  2. Add the CSS class declaration to the opening tag of the HTML element. ...
  3. Open up your CSS file. ...
  4. Create the CSS class and its declarations. ...
  5. Apply the CSS class to multiple HTML elements.
Jun 14, 2023

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 5694

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.