首頁 >web前端 >css教學 >CSS:簡單的深色模式

CSS:簡單的深色模式

Susan Sarandon
Susan Sarandon原創
2024-11-15 08:03:03531瀏覽

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!

以上是CSS:簡單的深色模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn