CSS 媒体功能 prefers-color-scheme 用于确定用户是更喜欢浅色主题还是深色主题。用户可以在设备设置或浏览器设置中选择自己喜欢的颜色模式,例如浅色或深色模式。
嵌入元素
- 您可以使用CSS 媒体功能 prefers-color-scheme 根据 SVG 和 iframe 嵌入的网页的颜色方案来更改它们的外观。SVG 必须用作图像 (<img src=“circle.svg” alt=“circle” />),而不是直接放在 HTML 中。
- 跨域 SVG 和 iframe 也可以使用 prefers-color-scheme。跨域元素是从与您当前所在的网站不同的网站加载的元素。
可能的值
- light − 此值表示浅色主题。
- dark − 此值表示深色主题。
语法
prefers-color-scheme: light|dark;
CSS prefers-color-scheme - light 值
以下示例演示了该元素将显示为带有蓝色文本的紫色背景,即使用户在其操作系统设置中请求了浅色主题 -
<html>
<head>
<style>
.light-theme {
background-color: red;
color: white;
}
@media (prefers-color-scheme: light) {
.light-theme {
background-color: violet;
color: blue;
}
}
</style>
</head>
<body>
<div class="light-theme">
This is a light theme.
</div>
</body>
</html>
CSS prefers-color-scheme - dark 值
以下示例演示了默认情况下,该元素具有红色背景色和黑色文本颜色。该元素将显示为带有蓝色文本的紫色背景,即使用户在其操作系统设置中请求了深色主题 -
<html>
<head>
<style>
.dark-theme {
background-color: red;
color: white;
}
@media (prefers-color-scheme: dark) {
.dark-theme {
background-color: violet;
color: blue;
}
}
</style>
</head>
<body>
<div class="dark-theme">
This is a dark theme.
</div>
</body>
</html>
CSS prefers-color-scheme - 检测深色或浅色主题
以下示例演示了媒体查询 @media (prefers-color-scheme: dark) 和 @media (prefers-color-scheme: light) 将根据用户首选的颜色主题对 .theme 类应用不同的样式 -
<html>
<head>
<style>
.theme {
background: green;
color: white;
}
@media (prefers-color-scheme: dark) {
.theme.dark-theme {
background: red;
color: white;
}
}
@media (prefers-color-scheme: light) {
.theme.light-theme {
background: yellow;
color: blue;
}
}
</style>
</head>
<body>
<p class="theme">Default Theme. The element will be displayed as a green background with white text.</p>
<p class="theme dark-theme">If the user has requested a dark color theme in their operating system the element will be displayed as a red background with white text.</p>
<p class="theme light-theme">If the user has requested a light color theme in their operating system the element will be displayed as a yellow background with blue text.</p>
</body>
</html>
CSS prefers-color-scheme - 颜色方案继承
以下示例演示如何使用 CSS 媒体功能 prefers-color-scheme 根据用户的首选颜色主题显示不同的 SVG 图像。
在此示例中,JavaScript 用于创建三个 SVG 图像:一个是粉红色背景色,一个是紫色背景色,另一个是由用户首选的颜色主题确定的背景颜色。
这是一个例子 -
<html>
<head>
</head>
<body>
<div>
<img />
</div>
<div style="color-scheme: light">
<img />
</div>
<div style="color-scheme: dark">
<img />
</div>
<script>
document.querySelectorAll("img").forEach(function(img) {
img.alt = "square";
img.src =
"data:image/svg+xml;base64," +
btoa(`
<svg width="100" height="100" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<style>
:root { color: pink }
@media (prefers-color-scheme: light) {
:root { color: violet }
}
</style>
<rect fill="currentColor" x="2" y="2" width="16" height="16"/>
</svg>
`);
});
</script>
</body>
</html>