---
title: "Detect Dark Mode"
description: "Using prefers-color-scheme to detect and respond to user’s dark mode preference. Practical notes and code examples on Detect."
url: "https://h3manth.com/scribe/detect-dark-mode/"
canonical_url: "https://h3manth.com/scribe/detect-dark-mode/"
markdown_url: "https://h3manth.com/scribe/blog/detect-dark-mode.md"
publishDate: "2020-02-13T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["javascript","css","dark-mode"]
word_count: 233
reading_time_minutes: 2
x_markdown_tokens: 602
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Detect Dark Mode

> Using prefers-color-scheme to detect and respond to user’s dark mode preference. Practical notes and code examples on Detect.

Detecting if the user preference is light or dark color theme is pretty easy with the `prefers-color-scheme` CSS media feature.

## Detecting in JavaScript

```javascript
const isDarkMode = window.matchMedia && 
  window.matchMedia('(prefers-color-scheme: dark)').matches;

Or maybe a more generic method:
javascript
const checkType = type => 
  window.matchMedia && 
  window.matchMedia(`(prefers-color-scheme: ${type})`).matches;

const mode = {
  is: {
    dark: checkType('dark'),
    light: checkType('light')
  }
};

mode.is.dark;  // true
mode.is.light; // false
```

`matchMedia(query)` returns a new `MediaQueryList` object with the parsed results of the specified media query string.

## Detecting in CSS

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

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

> **Note from the [spec](https://drafts.csswg.org/mediaqueries-5/#descdef-media-prefers-color-scheme):** User preferences can also vary by medium. For example, a user may prefer dark themes on a glowing screen, but light themes when printing. UAs are expected to take such variances into consideration.

## Handling Preference Changes

```javascript
window.matchMedia('(prefers-color-scheme: dark)')
  .addListener((e) => {
    const isDarkMode = e.matches;
    console.log(`${isDarkMode ? '🌚' : '🌞'}.`);
  });

## Force Setting Dark Mode
javascript
const forceDarkMode = () =>
  [...document.styleSheets[0].rules].forEach(rule => {
    const mediaText = rule.media && rule.media.mediaText || [];
    const hasColorScheme = mediaText.includes("prefers-color-scheme");
    const hasLightScheme = hasColorScheme && mediaText.includes("light");
    
    // Remove light mode if present
    if (hasLightScheme) {
      rule.media.deleteMedium("(prefers-color-scheme: light)");
    }
    
    // Append dark mode
    rule.media && rule.media.appendMedium("(prefers-color-scheme: dark)");
  });
```
