How to Implement Dark Mode in CSS & JS

shape
shape
shape
shape
shape
shape
shape
shape
How to Implement Dark Mode in CSS & JS

How to Implement Dark Mode in CSS & JS

Dark mode has become one of the most requested features in modern web design, enhancing user experience and reducing eye strain during nighttime browsing. In this guide, you’ll learn exactly how to implement dark mode in CSS and JavaScript—step by step. We’ll also cover best practices, common pitfalls, and an SEO checklist to help your site perform well in search results while providing an accessible, modern interface for users.

Why Implement Dark Mode on Your Website?

Before diving into the technical implementation, it’s important to understand why dark mode matters:

  • Improved readability and comfort: Dark mode reduces eye fatigue in low-light environments.
  • Battery efficiency: Especially for OLED screens, darker pixels use less power.
  • Modern aesthetics: Users expect sites to support light and dark themes in 2025 and beyond.
  • Accessibility: Offering theme options helps users with light sensitivity or vision preferences.

Now, let’s go through how to actually add dark mode to your website using CSS and JavaScript.

1. Implement Dark Mode Using CSS Only (Preferred Method)

The simplest way to implement dark mode is by using CSS custom properties and the prefers-color-scheme media query. This approach lets browsers automatically detect whether the user prefers a light or dark theme based on their system settings.

Step 1: Define CSS Variables

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

Step 2: Add the Dark Mode Media Query

@media (prefers-color-scheme: dark) {
  :root {
    --bg-color: #121212;
    --text-color: #ffffff;
  }
}

With this approach, your website automatically adjusts to the user’s system theme preference. However, many users like to toggle dark mode manually — which brings us to the next method.

2. Implement Dark Mode Toggle Using JavaScript

To give users manual control over dark mode, we can use JavaScript to toggle between light and dark themes dynamically.

Step 1: Set Up the HTML Structure

<button id="theme-toggle">Toggle Dark Mode</button>

Step 2: Define CSS Classes for Each Theme

body.light-mode {
  background-color: #ffffff;
  color: #000000;
}

body.dark-mode {
  background-color: #121212;
  color: #ffffff;
}

Step 3: Add JavaScript to Handle Theme Switching

const toggle = document.getElementById('theme-toggle');
const body = document.body;

// Load previously saved theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
  body.classList.add(savedTheme);
}

toggle.addEventListener('click', () => {
  if (body.classList.contains('dark-mode')) {
    body.classList.replace('dark-mode', 'light-mode');
    localStorage.setItem('theme', 'light-mode');
  } else {
    body.classList.replace('light-mode', 'dark-mode');
    localStorage.setItem('theme', 'dark-mode');
  }
});

This JavaScript snippet toggles between dark and light mode when the user clicks the button and saves their preference in localStorage for persistence across page reloads.

3. Combining CSS & JavaScript Approaches

The most effective implementation combines both the CSS and JS methods. You can use the system preference as the default (via CSS) and allow manual toggling through JavaScript for maximum flexibility.

// Detect system preference on first visit
if (!localStorage.getItem('theme')) {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.body.classList.add('dark-mode');
  } else {
    document.body.classList.add('light-mode');
  }
}

This approach gives users the best experience—automatic theme detection and manual override.

4. SEO & Accessibility Checklist for Dark Mode Implementation

While dark mode mainly affects UI design, it can indirectly impact SEO and user experience. Here’s a quick checklist to ensure your implementation aligns with SEO best practices:

Technical SEO Checklist

  • Ensure both light and dark modes use the same HTML structure and metadata.
  • Do not duplicate pages for light/dark themes (use CSS/JS only).
  • Optimize page load speed; avoid large theme-specific images.
  • Test your implementation on mobile and desktop for consistent results.

UX & Accessibility Checklist

  • Maintain sufficient color contrast between text and background (WCAG 2.1 compliance).
  • Use CSS variables for color control—easy to update and manage.
  • Save user preference in localStorage for a personalized experience.
  • Ensure icons and logos adapt to both themes (SVG color fills or multiple versions).

Performance Optimization Checklist

  • Use prefers-color-scheme for system-level dark mode support.
  • Minify CSS and JS to reduce file size.
  • Use lazy loading for images that appear only in dark mode.

5. Testing Dark Mode

Before deploying, test dark mode across multiple environments:

  • Browsers: Chrome, Safari, Firefox, and Edge.
  • Devices: Android and iOS devices with both dark/light preferences.
  • DevTools: Use Chrome DevTools > Rendering > “Emulate CSS prefers-color-scheme.”

Ensure that all UI elements (buttons, forms, links, cards, etc.) are visually consistent and accessible in both modes.

6. Common Mistakes to Avoid

  • Overriding inline styles: Inline CSS can prevent your theme changes from applying correctly. Use variables instead.
  • Forgetting contrast: Avoid low-contrast text colors; they harm readability and accessibility.
  • Ignoring icons: Many icons use static black/white fills—make sure they adapt dynamically.
  • Not saving preferences: If users have to re-toggle dark mode each visit, they may get frustrated.

7. Bonus: Adding Smooth Transition Effects

For a more polished experience, add a CSS transition when switching themes.

body {
  transition: background-color 0.3s ease, color 0.3s ease;
}

This subtle animation enhances UX by making theme changes feel smooth and modern.

8. Example: Complete Implementation

Here’s a simplified version putting everything together:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dark Mode Example</title>
<style>
  body.light-mode {
    background: #ffffff;
    color: #000000;
  }
  body.dark-mode {
    background: #121212;
    color: #ffffff;
  }
  body {
    transition: background 0.3s, color 0.3s;
  }
</style>
</head>
<body>
  <button id="theme-toggle">Toggle Dark Mode</button>
  <script>
    const toggle = document.getElementById('theme-toggle');
    const body = document.body;

    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      body.classList.add(savedTheme);
    } else {
      if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
        body.classList.add('dark-mode');
      } else {
        body.classList.add('light-mode');
      }
    }

    toggle.addEventListener('click', () => {
      if (body.classList.contains('dark-mode')) {
        body.classList.replace('dark-mode', 'light-mode');
        localStorage.setItem('theme', 'light-mode');
      } else {
        body.classList.replace('light-mode', 'dark-mode');
        localStorage.setItem('theme', 'dark-mode');
      }
    });
  </script>
</body>
</html>

9. How Dark Mode Impacts SEO and User Engagement

Although search engines don’t directly rank pages higher for offering dark mode, providing it can lead to better user metrics—like increased time on page and lower bounce rates—which indirectly improve SEO performance. A positive UX always contributes to long-term organic growth.

Also, dark mode implementation shows that your website is modern, responsive, and accessible—all signals that align with user trust and brand credibility.

FAQ: How to Implement Dark Mode in CSS & JS

1. Does dark mode affect SEO rankings?

No, dark mode itself doesn’t directly impact SEO rankings. However, it improves user experience, which can enhance engagement metrics that influence SEO indirectly.

2. What’s the easiest way to implement dark mode?

The easiest way is using the prefers-color-scheme CSS media query, which automatically adapts your site to the user’s system theme.

3. Should I store the user’s dark mode preference?

Yes. Use localStorage in JavaScript to save the user’s preference so it persists across sessions.

4. How do I make images adapt to dark mode?

Use transparent PNGs or SVGs that can change color dynamically via CSS filters or fills.

5. How do I test dark mode in Chrome?

Go to Chrome DevTools > Rendering > Emulate CSS Media Feature: prefers-color-scheme. Choose “dark” or “light” to preview each theme.

Conclusion

Learning how to implement dark mode in CSS and JS is an essential modern web development skill. It’s not only about aesthetics—it’s about enhancing usability, accessibility, and user satisfaction. Whether you’re creating a new website or updating an existing one, integrating a seamless dark mode experience can help you stand out and retain users.

For businesses looking to build professional websites with advanced UI/UX features and optimized SEO performance, WEBPEAK offers full-service Web Development, Digital Marketing, and SEO solutions to help your online presence thrive.

Popular Posts

No posts found

Follow Us

WebPeak Blog

Best SEO Company in London: How to Choose ROI-Driven Experts
November 2, 2025

Best SEO Company in London: How to Choose ROI-Driven Experts

By Digital Marketing

Looking for the best SEO company in London? Learn how to identify ROI-focused experts who combine strategy, data, and innovation for lasting growth.

Read More
Why Our London SEO Agency Delivers the Best Results in 2025
November 2, 2025

Why Our London SEO Agency Delivers the Best Results in 2025

By Digital Marketing

See why businesses trust our London SEO experts in 2025 for measurable growth through advanced keyword strategy, content optimization, and AI-powered solutions.

Read More
Top SEO Companies in London for Small Businesses
November 2, 2025

Top SEO Companies in London for Small Businesses

By Digital Marketing

Explore London’s top SEO companies for small businesses. Learn how expert-driven optimization can increase traffic, improve rankings, and boost conversions.

Read More