【问题标题】:Selecting subelements of an SVG template via CSS通过 CSS 选择 SVG 模板的子元素
【发布时间】:2015-01-18 01:41:33
【问题描述】:

我不确定从 HTML 文件中的通用内联 SVG“模板”调用的单个 SVG 实例的结构、选择和样式的正确标记。

<!-- 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 模板中,我有一个由几个 paths 组成的组 &lt;g&gt;,每个组都有一个类名。我已为该 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>

现在我尝试在 CSS 中选择/设置这些实例的元素,如下所示(尽管这种语法不起作用!):

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

#instance2 .outline {
    fill: green;
}

我认为这很容易,但我无法找出正确的方法来选择/设置&lt;use&gt; 一组通用路径的单个 SVG。

有什么想法吗?谢谢!

代码 sn-p 可在http://codepen.io/edhebert/pen/GgmKOo 上查看

【问题讨论】:

  • @RobertLongson 并非不可能。请参阅下面的答案。

标签: html css svg


【解决方案1】:

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

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

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

.. &lt;use&gt; 的后代将从&lt;use&gt; 元素继承 fill 颜色。但是所有后代都会继承这种颜色。

例如,如果您只想将特定颜色应用于&lt;use&gt; 内的一个元素,则可以使用另一种技术。然而,这种技术目前是有限的。

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

基本上,如果您想要重新use 的 SVG 元素,而不是在每个路径的“模板”内指定 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 中受支持——所以我认为您不会在生产环境中使用它。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2015-07-29
    • 1970-01-01
    • 2019-04-30
    • 2015-10-15
    相关资源
    最近更新 更多