2 min read

CSS prefers-color-scheme

The prefers-color-scheme CSS media feature is used to detect if the user has requested a light or dark color theme. This is usually a system-wide setting in the operating system (macOS, Windows, iOS, Android).

1. Syntax

It is used inside a @media query.

@media (prefers-color-scheme: dark) {
  /* Styles for users who prefer dark mode */
}

@media (prefers-color-scheme: light) {
  /* Styles for users who prefer light mode */
}

2. Values

  • light: The user has notified the system that they prefer a page that has a light theme (light background, dark text). This is often the default if no preference is expressed.
  • dark: The user has notified the system that they prefer a page that has a dark theme (dark background, light text).

3. Basic Usage

The most common pattern is to define CSS variables for colors and update them inside the media query.

:root {
  --bg-color: white;
  --text-color: black;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg-color: #121212;
    --text-color: <a href='/?search=%23ffffff' class='obsidian-tag'>#ffffff</a>;
  }
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

4. Relationship with color-scheme

  • color-scheme property: Tells the browser "I support dark mode, please render default form controls and scrollbars in dark mode".
  • prefers-color-scheme media query: Allows you to write custom CSS styles for that mode.

Ideally, you should use both. Or, use the newer light-dark() function which relies on the color-scheme property to switch values automatically.

programming/css/css programming/css/color-scheme programming/css/light-dark-function programming/css/css-variables programming/css/responsive-design