DEV Community

Cover image for Switching Modes: Implementing a Light-Dark Theme by CSS Only 🌗
Ram kumar Shrestha
Ram kumar Shrestha

Posted on

Switching Modes: Implementing a Light-Dark Theme by CSS Only 🌗

Switching between light and dark themes has become a must-have feature for modern websites, as most users prefer having control over their viewing preferences. This small yet impactful addition can significantly enhance usability, aesthetics, and overall user experience.

In this blog, we’ll explore how to implement a light-dark theme toggle using CSS and JavaScript, ensuring both accessibility and a seamless experience for your users.

Why Light-Dark Themes?

  • User Preferences: Mos users prefer dark themes to reduce eye strain, especially in low-light environments.

  • Aesthetic Appeal: A well-designed dark theme adds a modern touch to your website.

  • Device Compatibility: Many devices now support dark mode natively, and websites can complement this feature.

CSS's Powerful Light-Dark Property

CSS introduced a powerful property light-dark to simplify theme toggling. In this blog, we’ll explore how to use it with a straightforward example.

Example

  1. Simple HTML structure The first step is provide a button which will toggle the theme in the web browser.
<body id="content">
  <button id="theme-toggle">Switch Theme</button>
</body>
Enter fullscreen mode Exit fullscreen mode

Here, clicking the button will toggle the theme.

  1. Provide the CSS for theme toggle
#content {
   background-color: light-dark(#eeee, #424242);
}
Enter fullscreen mode Exit fullscreen mode

Here, #eee will be the background color for light theme and #424242 will be for the dark theme.

  1. Script to toggle the theme
const themeToggle = document.getElementById("theme-toggle");

themeToggle.addEventListener("click", () => {
  const content = document.getElementById("content");
  const currentTheme = content.style["color-scheme"];

 content.style["color-scheme"] = currentTheme === "dark" ? "light" : "dark";
});
Enter fullscreen mode Exit fullscreen mode

When the theme-toggle button is clicked, the script toggles the theme between light and dark modes dynamically.

Conclusion

Implementing a light-dark theme toggle is an essential feature for enhancing user experience and aligning with modern design trends. By leveraging the power of CSS and JavaScript, you can create an accessible, visually appealing, and user-friendly theme toggle for your website.

With this feature, you not only accommodate users’ preferences but also ensure compatibility with devices that support native dark modes. Adding a light-dark theme toggle is a small but meaningful step toward creating a more versatile and inclusive web experience.

Top comments (0)