Heim  >  Artikel  >  Web-Frontend  >  CSS: Einfacher Dunkelmodus

CSS: Einfacher Dunkelmodus

Susan Sarandon
Susan SarandonOriginal
2024-11-15 08:03:03452Durchsuche

CSS: Easy dark mode

A dark mode is a display option that switches the color theme of a website or application from a light background (with dark text) to a dark background (with light text). This mode has grown popular for its benefits in reducing eye strain in low-light environments, saving energy on devices with OLED screens, and offering a visually appealing alternative to traditional light themes.
Usually, you can toggle between 3 modes: dark, light and System theme setting.

Old way

Till now we've used the prefers-color-scheme CSS media feature:

The prefers-color-scheme CSS media feature is used to detect if a user has requested light or dark color themes. A user indicates their preference through an operating system setting (e.g. light or dark mode) or a user agent setting.

@media (prefers-color-scheme: dark) {
  .post {
    background: #753;
    color: #dcb;
  }
}

@media (prefers-color-scheme: light) {
  .post {
    background: #bcd;
    color: #334;
  }
}

As you can see, we need to maintain 2 themes, one for each mode.
Taking this approach in a large-scale application may be difficult.

New and better way

Luckily, CSS has introduced a new property to make our life easier, light-dark() and it is supported by all major browsers:

The light-dark() CSS function enables setting two colors for a property - returning one of the two colors options by detecting if the developer has set a light or dark color scheme or the user has requested light or dark color theme - without needing to encase the theme colors within a prefers-color-scheme media feature query.

:root {
  color-scheme: light dark;
}

body {
  color: light-dark(#292524, #f5f5f4);
  background-color: light-dark(#f5f5f4, #292524);
}

Just use the light-dark() property on each element we wish to toggle between modes, that's it!

Das obige ist der detaillierte Inhalt vonCSS: Einfacher Dunkelmodus. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn