prefers-color-scheme

prefers-color-scheme CSS media feature 用于检测用户的系统主题是浅色或深色。

语法

no-preference
表示用户未指定操作系统主题。其作为 布尔值 时以false输出。
light
表示用户的操作系统是浅色主题。
dark
表示用户的操作系统是深色主题。

样例

这个例子使用了一个有黑色背景和白色文字的元素,当用户使用浅色主题时,会翻转黑白颜色。

HTML

<div class="day">Day (initial)</div>
<div class="day light-scheme">Day (changes in light scheme)</div>
<div class="day dark-scheme">Day (changes in dark scheme)</div> <br>

<div class="night">Night (initial)</div>
<div class="night light-scheme">Night (changes in light scheme)</div>
<div class="night dark-scheme">Night (changes in dark scheme)</div>

CSS

.day   { background: #eee; color: black; }
.night { background: #333; color: white; }

@media (prefers-color-scheme: dark) {
  .day.dark-scheme   { background:  #333; color: white; }
  .night.dark-scheme { background: black; color:  #ddd; }
}

@media (prefers-color-scheme: light) {
  .day.light-scheme   { background: white; color:  #555; }
  .night.light-scheme { background:  #eee; color: black; }
}

.day, .night {
  display: inline-block;
  padding: 1em;
  width: 7em;
  height: 2em;
  vertical-align: middle;
}

Result

规范

规范 状态 注释

Media Queries Level 5
prefers-color-scheme

Editor's Draft Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
prefers-color-scheme media featureChrome Full support 76Edge No support NoFirefox Full support 67IE No support NoOpera Full support 62Safari Full support 12.1WebView Android Full support 76Chrome Android Full support 76Firefox Android Full support 67Opera Android Full support 54Safari iOS Full support 13Samsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support

相关资料