light-dark() 并不总是与 prefers-color-scheme 相同

I've thought that the new light-dark() CSS function can be used as a drop-in replacement for prefers-color-scheme media queries. Today I learned that they don't always behave the same.

我曾认为 新的 light-dark() CSS 函数 可以作为 prefers-color-scheme 媒体查询的替代品。今天我了解到它们并不总是表现得一样。

Here's how MDN describes the new color function:

以下是 MDN 对新颜色函数的描述:

The light-dark() CSS <color> function enables setting two colors for a property [...] without needing to encase the theme colors within a prefers-color-scheme media feature query.

light-dark() CSS <color> 函数允许为一个属性设置两种颜色 [...] 而无需将主题颜色封装在 prefers-color-scheme 媒体特性查询中。

If you wonder about light-dark() browser support, here we go.

如果你想知道 light-dark() 的浏览器支持情况,下面是相关信息。

Now, I thought you could replace all your verbose color scheme queries with short light-dark() one-liners.

现在,我原以为你可以用简短的 light-dark() 单行代码替换掉所有冗长的颜色方案查询。

/* The old way of flipping dark mode styles */
.someElement {
  background: #eee;
  color: #333;
  border-color: #ddd;

  @media (prefers-color-scheme: dark) {
    background: #333;
    color: #eee;
    border-color: #444;
  }
}

/* The new way of flipping dark mode styles */
.someElement {
  background: light-dark(#eee, #333);
  color: light-dark(#333, #eee);
  border-color: light-dark(#ddd, #444);
}

Unfortunately, things aren't that easy.

不幸的是,事情并没有那么简单。

The first thing to realize is that light-dark() requires a properly set color-scheme. Here's MDN again:

首先要意识到的是 light-dark() 需要 一个正确设置的 color-scheme。MDN 再次提到:

To enable support for the light-dark() color function, the color-scheme must have a value of light dark, usually set on the :root pseudo-class.

要启用对 light-dark() 颜色函数的支持,color-scheme 必须具有 light dark 的值,通常设置在 :root 伪类上。

Without setting color-scheme: light dark; on :root or a surrounding container, the light-dark() function won't work. Flip your operating system's color theme and you'll see that light-dark() doesn't work below.

如果不在 :root 或周围容器上设置 color-scheme: light dark;,那么 light-dark() 函数将无法工作。切换你的操作系统的颜色主题,你会看到下面的 light-dark() 不起作用。

The prefers-color-scheme que...

开通本站会员,查看完整译文。

ホーム - Wiki
Copyright © 2011-2025 iteam. Current version is 2.148.1. UTC+08:00, 2025-11-29 15:08
浙ICP备14020137号-1 $お客様$