通过 CSS 选择 SVG 模板的子元素

Selecting subelements of an SVG template via CSS

我不确定从 HTML 文件中的通用内联 SVG "template" 调用的单个 SVG 实例的结构、select 和样式设置是否正确。

<!-- first instance to style -->
<svg id="instance1" viewBox="0 0 799.9 177.8">
  <use xlink:href="#template">
</svg> 
<!-- second instance, want different styles -->
<svg id="instance2" viewBox="0 0 799.9 177.8">
  <use xlink:href="#template">
</svg>

在我的 SVG 模板中,我有一组 <g>,由几个 path 组成,每个组都有一个 class 名称。我已经为该 SVG 组指定了一个 ID template,并且正在调用它的实例。

<!-- first instance to style -->
<svg id="instance1" viewBox="0 0 799.9 177.8">
  <use xlink:href="#template">
</svg>

<!-- second instance, want to apply different styles -->
<svg id="instance2" viewBox="0 0 799.9 177.8">
  <use xlink:href="#template">
</svg>

现在,我正在尝试 select/style 元素 CSS 中的这些实例,如下所示(尽管此语法不起作用!):

/* want to style each instance differently */   
#instance1 .outline {
    fill: red;
}

#instance2 .outline {
    fill: green;
}

我认为这很容易,但我想不出 select/style 这些单独的 SVG <use> 一组通用路径的正确方法。

有什么想法吗?谢谢!

可在 http://codepen.io/edhebert/pen/GgmKOo

查看代码片段

<use> 的内容被克隆到影子 DOM 中,因此无法使用 CSS 我们知道的正常直接方式直接选择和设置样式。

在继续之前,请注意您可以通过将样式应用于 <use> 本身来将样式应用于 <use> 元素的内容。例如,这样做:

<svg id="instance1" viewBox="0 0 799.9 177.8"> <use xlink:href="#template" fill="maroon"> </svg>

.. <use> 的后代将 继承 来自 <use> 元素的 fill 颜色。但是所有后代都会继承这种颜色。

例如,如果您只想将特定颜色应用于 <use> 中的一个元素,则可以使用另一种技术。但是,此技术目前受到限制。

该技术利用 CSS currentColor 变量发挥作用。 Fabrice Weinberg 在 this blog post over at Codepen 中写到了这项技术。

基本上,如果您有一个想要重新 use 的 SVG 元素,而不是在每个路径的 "template" 内指定 fill 颜色,您可以这样做:

<g> <path fill="currentColor" d="..." /> </g>

然后,在你的 CSS 中,你可以指定你想要的 color,知道这种颜色将应用于上述路径——因为这就是 currentColor有效。

use#instance1 { fill: deepPink; /* will be inherited by contents of `use` */ color: #eee; /* will be inherited by the path element */ }

其他人通过使用用户定义的 CSS 变量来完成完全相同的事情,进一步采用了这种技术。你可以阅读它 here。 CSS 变量技术与 Weinberg 的技术相同,除了您可以定义任意数量的变量,在模板中使用它们,然后在您的 CSS 中指定它们的值——这些值随后将无论您在模板中定义了这些变量,它们都会被它们使用。 此技术有效,但 CSS 变量目前仅在 Firefox 中受支持——因此我认为您不会在生产中使用它。

希望这对您有所帮助。