DEV Community

Juwan Petty
Juwan Petty

Posted on

9 5

prefers-color-scheme 🌗

If you want to see an example of prefers-color-scheme in action, here's a CodePen link.

prefers-color-scheme is a CSS media query that detects the current theme preference of the user's operating system.

@media (prefers-color-scheme: dark) {
  .element {
    background: black;
    color: white;
  }
}

The prefers-color-scheme media query has two values that you can specify: light and dark. These values allow you to customize the theme of the page with CSS depending on the user's preference.

light: Indicates that the user has notified the system that they prefer a page that has a light theme (dark text on light background).

dark: Indicates that the user has notified the system that they prefer a page that has a dark theme (light text on dark background).

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

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

For the scenario where a user has no preference, you can pass no-preference to add a "default" theme to the page.

Browser Support

At the time of writing this post, browser support for prefers-color-scheme sits at 78% with Edge and Opera Mini along with other mobile browsers not supporting the CSS media query.

Resources

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!