# DarkMode Adaptation Guide
# background
IOS and Android respectively from iOS 13 and Android 10 (different manufacturers are not the same, some Android 9 also support) began to add dark mode support,Each big browser begins to support brunet mode in succession, WeChat iOS client side 7.0.12, Android client side 7.0.13 also supported brunet mode, the consistency that after webpage side adapts brunet mode to will improve user experience further.
# How to switch to dark mode
IOS: "Settings" -- "Display and Brightness" -- "Appearance," select "Dark"
Android (different manufacturers may be slightly different, the name is not the same): "tie settings" - "display" - "dark mode."
# Adaptation guidelines
WeChat The built-in browser implements support for dark mode based on Web standards.It can be adapted in the same way as general Web page adaptations, such as:
# Declaration color-scheme
There are two ways:
- Meta: Declares' in
head
'. States that the current page supports both light and dark modes. If the system switches to dark mode, the default browser style also switches to dark mode. - CSS: The following CSS can also achieve the effect of the above meta declaration
:root {
color-scheme: light dark;
}
Note: This declaration does not automatically adapt the page, only affects the browser default
More information can be found in the W3C document < CSS Color Adjustment Module Level 1 >
# Media queries via CSS
:root {
color-scheme: light dark;
background: white;
color: black;
}
@media (prefers-color-scheme: dark) {
:root {
background: black;
color: white;
}
}
In the case of more colors, it is recommended to use CSS variables to manage color values.
:root {
color-scheme: light dark;
--nav-bg-color: #F7F7F7;
--content-bg-color: #FFFFFF;
--font-color: rgba(0,0,0,.9);
}
@media (prefers-color-scheme: dark) {
:root {
--nav-bg-color: #2F2F2F;
--content-bg-color: #2C2C2C;
--font-color: rgba(255, 255, 255, .8);
}
}
:root {
color: var(--font-color)
}
.header {
background-color: var(--nav-bg-color);
}
.content {
background-color: var(--content-bg-color);
}
# The picture fits
Use thepicture
+source
tag to set the picture url in different modes.
<picture>
<!-- 深色模式下的图片 -->
<source srcset="dark.jpg" media="(prefers-color-scheme: dark)" />
<!-- 默认模式下的图片 -->
<img src="light.jpg"/>
</picture>
# Determine the current mode in JavaScript & listen for mode changes
Using thematchMedia
method, the specific usage refer to the following example:
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
function darkModeHandler() {
if (mediaQuery.matches) {
console.log('现在是深色模式')
} else {
console.log('现在是浅色模式')
}
}
// Judging the current pattern
darkModeHandler()
// Changes in listening patterns
mediaQuery.addListener(darkModeHandler)