font-palette

Baseline 广泛可用 *

此功能已成熟,可跨多种设备和浏览器版本使用。自 ⁨2022 年 11 月⁩起,所有浏览器均支持此功能。

* 此特性的某些部分可能存在不同级别的支持。

font-palette CSS 属性允许指定彩色字体中包含的众多调色板之一,用户代理可以将其用于字体。用户还可以通过使用 @font-palette-values at-rule 来覆盖调色板中的值或创建新的调色板。

注意:在为字体着色时,font-palette 调色板优先。即使使用 !important 指定,color 属性也不会覆盖字体调色板。

语法

css
/* Using a font-defined palette */
font-palette: normal;

/* Using a user-defined palette */
font-palette: --one;

/* Creating a new palette by blending two others */
font-palette: palette-mix(in lch, --blue, --yellow);

normal

指定用于字体的默认颜色调色板或默认字形着色(由字体创建者设置)。使用此设置,将渲染字体中索引为 0 的调色板。

light

指定字体中第一个匹配“light”的调色板,用于字体。某些字体包含元数据,用于识别适用于浅色(接近白色)背景的调色板。如果字体没有此元数据,则 light 值的行为与 normal 相同。

dark

指定字体中第一个匹配“dark”的调色板,用于字体。某些字体包含元数据,用于识别适用于深色(接近黑色)背景的调色板。如果字体没有此元数据,则该值的行为与 normal 相同。

<palette-identifier>

允许您使用 @font-palette-values at-rule 为字体调色板指定自己的值。此值使用 <dashed-ident> 格式指定。

palette-mix()

通过按指定百分比和颜色插值方法混合两个 font-palette 值来创建新的 font-palette 值。

正式定义

初始值normal
应用于所有元素和文本。它也适用于 ::first-letter::first-line
继承性
计算值同指定值
动画类型由计算值

正式语法

font-palette = 
normal |
light |
dark |
<palette-identifier> |
<palette-mix()>

<palette-mix()> =
palette-mix( <color-interpolation-method> , [ [ normal | light | dark | <palette-identifier> | <palette-mix()> ] && <percentage [0,100]>? ]#{2} )

<color-interpolation-method> =
in [ <rectangular-color-space> | <polar-color-space> <hue-interpolation-method>? | <custom-color-space> ]

<rectangular-color-space> =
srgb |
srgb-linear |
display-p3 |
display-p3-linear |
a98-rgb |
prophoto-rgb |
rec2020 |
lab |
oklab |
<xyz-space>

<polar-color-space> =
hsl |
hwb |
lch |
oklch

<hue-interpolation-method> =
[ shorter | longer | increasing | decreasing ] hue

<custom-color-space> =
<dashed-ident>

<xyz-space> =
xyz |
xyz-d50 |
xyz-d65

示例

指定深色调色板

此示例允许您使用字体创建者标记为深色(最适合接近黑色的背景)的第一个调色板。

css
@media (prefers-color-scheme: dark) {
  .banner {
    font-palette: dark;
  }
}

在两个调色板之间进行动画

此示例说明了如何对 font-palette 值更改进行动画处理,以创建平滑的字体动画。

HTML

HTML 包含一个要动画处理的段落文本

html
<p>color-palette<br />animation</p>

CSS

在 CSS 中,我们从 Google Fonts 导入一个名为 Nabla彩色字体,并使用 @font-palette-values at-rule 定义两个自定义 font-palette 值。然后我们创建 @keyframes,在这些调色板之间进行动画,并将此动画应用于我们的段落。

css
@import "https://fonts.googleapis.com/css2?family=Nabla&display=swap";

@font-palette-values --blue-nabla {
  font-family: "Nabla";
  base-palette: 2; /* this is Nabla's blue palette */
}

@font-palette-values --grey-nabla {
  font-family: "Nabla";
  base-palette: 3; /* this is Nabla's grey palette */
}

@keyframes animate-palette {
  from {
    font-palette: --grey-nabla;
  }

  to {
    font-palette: --blue-nabla;
  }
}

p {
  font-family: "Nabla", fantasy;
  font-size: 5rem;
  margin: 0;
  text-align: center;
  animation: animate-palette 4s infinite alternate linear;
}

结果

输出如下所示

注意:仍然实现 discrete font-palette 动画的浏览器将在两个调色板之间切换,而不是平滑地动画。

规范

规范
CSS 字体模块第 4 级
# font-palette-prop

浏览器兼容性

另见