DEV Community

Cover image for How to Enable Dark Mode Using CSS

How to Enable Dark Mode Using CSS

Introduction

Dark mode has become a popular option in many applications and websites, providing a comfortable viewing experience, especially in low-light environments. In this article, we will explore how to enable dark mode on your website using just CSS.

Enabling Dark Mode with Media Query

You can use a media query to check if the user prefers dark mode. Here’s how to do it:

@media (prefers-color-scheme: dark) {
  body {
    background-color: #121212;
    color: #ffffff;
  }

  /* Add more rules as needed */
  a {
    color: #bb86fc;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the media query checks if users prefer dark mode and changes the background and text colors accordingly.

Switching Between Dark and Light Mode Using JavaScript

You can add a button that allows users to toggle between dark and light modes. Here’s an example of how to do that:

HTML

<button id="toggle-dark-mode">Toggle Dark Mode</button>
Enter fullscreen mode Exit fullscreen mode

CSS

body {
  background-color: #ffffff;
  color: #000000;
  transition: background-color 0.3s, color 0.3s;
}

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

a {
  color: #1a0dab;
}

body.dark-mode a {
  color: #bb86fc;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

const toggleButton = document.getElementById('toggle-dark-mode');
toggleButton.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
});
Enter fullscreen mode Exit fullscreen mode

Saving User Preferences with Local Storage

To save the user's preference for dark mode, you can use Local Storage:

JavaScript

const toggleButton = document.getElementById('toggle-dark-mode');

toggleButton.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
  if (document.body.classList.contains('dark-mode')) {
    localStorage.setItem('dark-mode', 'true');
  } else {
    localStorage.setItem('dark-mode', 'false');
  }
});

window.onload = () => {
  if (localStorage.getItem('dark-mode') === 'true') {
    document.body.classList.add('dark-mode');
  }
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

Enabling dark mode on your website is not only an aesthetic feature but also enhances the user experience by making your site easier on the eyes. Using CSS and JavaScript, you can provide a dark mode option in a simple and efficient manner. Try these steps on your website and enjoy the benefits of dark mode!

Top comments (0)