the Chromium logo

The Chromium Projects

Detecting dark mode in polymer

How to check for dark mode in Polymer

Prerequisites

Polymer, CSS @media at-rule

Problem

In a Polymer website or application, I want to detect the color scheme of the browser (light mode or dark mode). I want to use this value as a JavaScript variable.

Solution

Use iron-media-query!

  1. Import the library into your custom element's JS file using:

    import '//resources/polymer/v3_0/iron-media-query/iron-media-query.js';
    
  2. Create a declared property in your custom element that will store the dark mode boolean value.

    static get properties() {
      return {
        isDarkModeEnabled_: {type: Boolean},
      };
    }
    
  3. Add the iron-media-query element into your custom element's HTML file.

    The query attribute can contain any valid CSS @media at-rule (see "@media" from MDN), but in this case we'll check for dark mode.

    The query-matches attribute should contain the Polymer property that you want the boolean query result to bind to. Remember to use curly brackets to allow two-way binding.

    <style>
    </style>
    <iron-media-query
      query="(prefers-color-scheme: dark)"
      query-matches="">
    </iron-media-query>
    <div>
      // The body of your custom element
    </div>
    
  4. You can now use your bound property (isDarkModeEnabled_ in this example) in your element's code!

    ...
    if (this.isDarkModeEnabled_) {
      showDarkModeIllustration();
    } else {
      showLightModeIllustration();
    }
    ...
    

Example CL

References

Comment/Discussion

iron-media-query can be used for other applications, including checking for screen width, screen height, device orientation, and whether the user prefers reduced motion.

How to check for dark mode in CSS

You can use the @media at-rule to check for dark mode in CSS:

/* Apply light mode styles */
body {
  background-color: white;
}

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