--- title: prefers-color-scheme slug: Web/CSS/@media/prefers-color-scheme tags: - CSS - Web - prefers-color-scheme - 参考 - 媒体查询 translation_of: Web/CSS/@media/prefers-color-scheme ---
prefers-color-scheme
CSS 媒体特性用于检测用户是否有将系统的主题色设置为亮色或者暗色。
no-preference
false
。light
dark
译者注:“未得知”、“已告知”等用语,英文原文如此。
“未得知”可理解为:浏览器的宿主系统不支持设置主题色,或者支持主题色并默认为/被设为了未设置/无偏好。
“已告知”为:浏览器的宿主系统支持设置主题色,且被设置为了亮色或者暗色。
目前,若结果为 no-preference
,无法通过此媒体特性获知宿主系统是否支持设置主题色,或者用户是否主动将其设置为无偏好。出于隐私保护等方面的考虑,用户或用户代理也可能在一些情况下在浏览器内部将其设置为 no-preference
。
这个例子使用了一个有黑色背景和白色文字的元素,当用户使用浅色主题时,会翻转黑白颜色。
<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>
.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; }
{{EmbedLiveSample("Examples")}}
规范 | 状态 | 注释 |
---|---|---|
{{SpecName('CSS5 Media Queries', '#descdef-media-prefers-color-scheme', 'prefers-color-scheme')}} |
{{Spec2('CSS5 Media Queries')}} | Initial definition. |
{{Compat("css.at-rules.media.prefers-color-scheme")}}