更简单的明暗模式切换:light-dark() 即将支持图片!

Back in 2023, I wrote about the future of CSS color switching using the then-novel light-dark() function. It was a game-changer for colors, allowing us to ditch the repetitive @media (prefers-color-scheme: ...) blocks for simple property declarations.

2023 年,我写过一篇关于 CSS 颜色切换的未来 的文章,使用当时新颖的 light-dark() 函数。这对颜色来说是一个游戏规则改变者,让我们能够放弃重复的 @media (prefers-color-scheme: ...) 代码块,转而使用简单的属性声明。

But there was one glaring limitation: it only works for colors. If you wanted to swap out a background image, a mask, or a logo based on the user’s color scheme, you were stuck doing things the “old” way.

但是有一个明显的限制:它仅适用于颜色。如果您想根据用户的颜色方案交换背景图像、蒙版或徽标,就只能用“旧”方法了。

Well, I have good news. The spec has been updated, and light-dark() is being extended to support images.

嗯,我有好消息。规范已经更新,light-dark() 正在扩展以支持图像。

~

~

The Missing Piece

缺失的部分

As a recap, in CSS, you have to write something like this if you want to set background-images for light and dark mode:

作为回顾,在 CSS 中,如果你想为浅色和深色模式设置背景图像,你必须写像这样的内容:

:root {
  --bg-image: url(light-pattern.png);
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg-image: url(dark-pattern.png);
  }
}

.element {
  background-image: var(--bg-image);
}

This code has downsides: The necessary parts can be scattered all over the place and it only checks the global color-scheme preference without respecting local color-scheme overrides done with the color-scheme CSS property.

这段代码有缺点:必要部分可能散布各处,而且它只检查全局 color-scheme 偏好,而不尊重使用color-scheme CSS 属性进行的本地 color-scheme 覆盖。

Thanks CSS light-dark() we can keep our code closely together, and can respond to the local used color-scheme value. In it’s updated form – in which light-dark() now also supports <image> values – that whole block can be collapsed into a single rule, and we can make it respect local color-scheme overrides:

感谢 CSS light-dark(),我们可以将代码紧密地放在一起,并响应本地使用的 color-scheme 值。在其更新形式中——light-dark() 现在也支持 <image> 值——整个代码块可以折叠成一个单一规则,并且我们可以让它尊重本地的 color-scheme 覆盖:

.element {
  color-scheme: dark;
  background-image: light-dark(url(light-pattern.png), url(dark-patter...
开通本站会员,查看完整译文。

Главная - Вики-сайт
Copyright © 2011-2026 iteam. Current version is 2.155.0. UTC+08:00, 2026-03-24 04:44
浙ICP备14020137号-1 $Гость$