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.
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.
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中文網其他相關文章!