21: 在 标签中使用两种颜色

我们了解到使用 <use> 插入 SVG 代码的一个限制是,你无法编写影响其中的复合 CSS 选择器。例如

<svg class="parent">
  <!-- shadow DOM boundary is effectively here -->
  <use class="child">
     <!-- stuff <use> references gets cloned in here --> 
  </use>
  <!-- end shadow DOM boundary -->
</svg>

该阴影 DOM 边界阻止了类似以下的选择器:

/* nope */
.parent .child {
}

生效。也许有一天我们会得到一个可以穿透该阴影 DOM 边界的 CSS 选择器,但截至目前还没有。

你仍然可以在 <svg> 父元素上设置填充,它会级联到子元素,但这只能让你获得一种颜色(记住不要在这些形状上设置表示样式的 fill 属性!)。

Fabrice Weinberg 想出了一个巧妙的小技巧来使用两种颜色,它利用了 CSS 中的 currentColor 关键字。

在任何你想要设置填充的形状上设置 fill CSS 属性为 currentColor

.shape-1, .shape-2 {
  fill: currentColor;
}

这样,当你设置父 <svg> 元素的颜色属性时,它也会级联到子元素。它本身不会做任何事情(除非你在里面有 <text> 元素),但是 currentColor 基于 color,所以你可以用它来做其他事情。

svg.variation-1 {
  fill: red;
  color: orange;
}

svg.variation-2 {
  fill: green;
  color: lightblue;
}

演示

查看 CodePen 上 Chris Coyier (@chriscoyier) 的 CodePen Logo 作为内联 SVG