🚀 UllrichLumina

How to detect if the OS is in dark mode in browsers

How to detect if the OS is in dark mode in browsers

📅 | 📂 Category: Css

Navigating the ever-evolving landscape of web development requires staying ahead of the curve, and one such curve is the rising popularity of dark mode. As users increasingly embrace darker interfaces for their improved readability and reduced eye strain, it’s crucial for developers to adapt their websites to seamlessly integrate with this preference. This article delves into the essential techniques for detecting whether a user’s operating system is set to dark mode, allowing you to dynamically adjust your website’s styling for an optimal user experience. Learn how to leverage CSS and JavaScript to create a truly responsive and user-centric web design.

Understanding Dark Mode Detection

Detecting a user’s preferred color scheme is paramount for providing a cohesive and visually appealing experience. Mismatch between a website’s color palette and the OS’s color scheme can lead to jarring contrasts and diminished readability. By accurately detecting dark mode, you can tailor your website’s styling to harmonize with the user’s environment, ensuring a comfortable and engaging browsing experience. This involves using specific media queries and JavaScript APIs to ascertain the user’s preference and dynamically apply appropriate styles.

Dark mode preference is typically managed at the operating system level. Users can choose between light and dark themes, and this selection cascades down to affect the appearance of applications and websites, unless specifically overridden. Therefore, your website needs to be aware of this OS-level setting to provide the best possible visual experience.

Using CSS Media Queries for Dark Mode Detection

CSS media queries provide a powerful and efficient mechanism for detecting dark mode preferences directly within your stylesheets. The prefers-color-scheme media query allows you to specify different styles based on the user’s preferred color scheme, eliminating the need for JavaScript intervention in many cases. This approach is straightforward and performant, contributing to a smoother user experience.

<style> body { background-color: fff; / Default light mode / color: 000; } @media (prefers-color-scheme: dark) { body { background-color: 000; / Dark mode styles / color: fff; } } </style> 

This code snippet showcases the basic implementation of the prefers-color-scheme media query. The first block sets default styles for light mode, while the nested block within the media query applies specific styles when the user’s OS is set to dark mode. This ensures your website adapts seamlessly to the user’s preferred color scheme.

Leveraging JavaScript for Enhanced Dark Mode Control

While CSS media queries are excellent for basic dark mode detection, JavaScript provides greater flexibility and control. Using the window.matchMedia API, you can not only detect the current color scheme but also dynamically update styles as the user changes their preference in real-time. This allows for more sophisticated and interactive dark mode implementations.

<script> const colorSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)'); function handleColorSchemeChange(e) { if (e.matches) { // Apply dark mode styles } else { // Apply light mode styles } } colorSchemeQuery.addEventListener('change', handleColorSchemeChange); // Initial check handleColorSchemeChange(colorSchemeQuery); </script> 

This JavaScript code demonstrates how to use window.matchMedia to detect and respond to changes in the user’s color scheme preference. The addEventListener ensures that your website dynamically updates its styling whenever the user toggles dark mode, providing a seamless and responsive user experience.

Best Practices for Dark Mode Implementation

Implementing dark mode effectively involves more than simply inverting colors. Consider contrast, accessibility, and user experience. High contrast ratios are crucial for readability, especially for users with visual impairments. Testing your implementation thoroughly across different browsers and devices is essential to ensure a consistent and accessible experience for everyone.

  • Prioritize Accessibility: Ensure sufficient contrast between text and background.
  • Test Thoroughly: Validate your implementation across various browsers and devices.

For a deeper dive into accessibility guidelines, refer to the Web Content Accessibility Guidelines (WCAG).

WCAG Contrast GuidelinesA real-world example of effective dark mode implementation is seen on major platforms like Twitter and GitHub, where the transition between light and dark modes is seamless and visually appealing.

Testing and Debugging Your Dark Mode Implementation

Rigorous testing is crucial to ensure your dark mode implementation functions correctly across all browsers and devices. Use browser developer tools to simulate different color schemes and test your styles. Consider using automated testing tools to streamline the process and catch potential issues early on. This diligent approach will contribute to a polished and reliable user experience.

Emulate dark mode in browser developer tools to quickly preview and adjust your dark mode styles. This allows for rapid iteration and ensures your design adapts seamlessly to different color scheme preferences.

Remember that user preferences are paramount. Providing a toggle switch to allow users to manually override the system setting can enhance user control and satisfaction, catering to individual needs and preferences.

  1. Use browser developer tools to simulate dark mode.
  2. Test on different browsers and devices.
  3. Consider providing a manual toggle option.

Choosing the right approach—CSS, JavaScript, or a combination—depends on your project’s complexity and specific requirements. For simple websites, CSS media queries may suffice, while complex applications may benefit from the dynamic control offered by JavaScript.

(Featured Snippet Optimized) Learn more about advanced dark mode techniques.

  • User preference
  • Media query

FAQ

How can I detect dark mode on older browsers? Older browsers that don’t support prefers-color-scheme may require JavaScript workarounds or polyfills to detect the user’s OS settings.

[Infographic Placeholder - Illustrating CSS and JavaScript Dark Mode Implementation] By implementing effective dark mode detection and styling, you enhance user experience, demonstrating a commitment to modern web development practices. This attention to detail contributes to user satisfaction and strengthens your brand’s online presence. Embracing these techniques allows you to create a more inclusive and visually appealing website for all users. Explore these methods, and tailor your approach to create an engaging and user-friendly experience regardless of the chosen color scheme.

Start optimizing your website for dark mode today and provide a superior browsing experience for your users. Dive deeper into the resources linked throughout this article to master the intricacies of dark mode implementation and stay ahead of the curve in web development best practices. MDN Web Docs: prefers-color-scheme Web.dev: prefers-color-scheme

Question & Answer :
Similar to “How to detect if OS X is in dark mode?” only for browsers.

Has anyone found if there is a way to detect if the user’s system is in the new OS X Dark Mode in Safari/Chrome/Firefox?

We would like to change our site’s design to be dark-mode friendly based on the current operating mode.

The new standard is registered on W3C in Media Queries Level 5.

NOTE: currently only available in Safari Technology Preview Release 68

In case user preference is light:

/* Light mode */ @media (prefers-color-scheme: light) { body { background-color: white; color: black; } } 

In case user preference is dark:

/* Dark mode */ @media (prefers-color-scheme: dark) { body { background-color: black; color: white; } } 

There is also the option no-preference in case a user has no preference. But I recommend you just to use normal CSS in that case and cascade your CSS correctly.

EDIT (7 dec 2018):

In Safari Technology Preview Release 71 they announced a toggle switch in Safari to make testing easier. I also made a test page to see the browser behaviour.

If you have Safari Technology Preview Release 71 installed you can activate through:

Develop > Experimental Features > Dark Mode CSS Support

Then if you open the test page and open the element inspector you have a new icon to toggle Dark/Light mode.

toggle dark/light mode


EDIT (11 feb 2019): Apple ships in the new Safari 12.1 dark mode


EDIT (5 sep 2019): Currently 25% of the world can use dark mode CSS. Source: caniuse.com

Upcoming browsers:

  • iOS 13 ( I guess it will be shipped next week after Apple’s Keynote)
  • EdgeHTML 76 (not sure when that will be shipped)

EDIT (5 nov 2019): Currently 74% of the world can use dark mode CSS. Source: caniuse.com


EDIT (3 Feb 2020): Microsoft Edge 79 supports dark mode. (released on 15 Jan 2020)

My suggestion would be: that you should consider implementing dark mode because most of the users can use it now (for night-time users of your site).

Note: All major browsers are supporting dark mode now, except: IE, Edge


EDIT (19 Nov 2020): Currently 88% of the world can use dark mode CSS. Source: caniuse.com

CSS-framework Tailwind CSS v2.0 supports dark-mode. (released on 18 Nov 2020)


EDIT (2 Dec 2020):

Google Chrome adds Dark Theme emulation to Dev Tools. Source: developer.chrome.com


EDIT (2 May 2022):

Currently 90% of the world can use dark mode CSS. Source: caniuse.com


EDIT (23 Jan 2024):

Currently 96.5% of the world can use dark mode CSS. Source: caniuse.com