Home > Web Front-end > CSS Tutorial > CSS: Easy dark mode

CSS: Easy dark mode

Susan Sarandon
Release: 2024-11-15 08:03:03
Original
527 people have browsed it

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;
  }
}
Copy after login

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);
}
Copy after login

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

The above is the detailed content of CSS: Easy dark mode. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template