Change Part of Symbol Color SVG

2019-08-10 17:24发布

I have an SVG symbol, basically three paths with an all black stroke. This symbol is used heavily across my SVG document using the use tag.

Sometimes i just want to change only one stroke of the instances of the symbol, like color variations, How can i achieve this using SVG+CSS, knowing that I used 'use' to create the symbol instances.

标签: svg
3条回答
疯言疯语
2楼-- · 2019-08-10 18:14

It is possible. You can't style the dereferenced symbol contents directly with CSS. But you can style the parent <use> element and have that colour inherit into the symbol. See the answers to the following question for examples.

How to style one particular SVG path in CSS?

查看更多
放荡不羁爱自由
3楼-- · 2019-08-10 18:15

According to the SVG 1.1 spec on the use element:

The effect of a ‘use’ element is as if the contents of the referenced element were deeply cloned into a separate non-exposed DOM tree […] The SVG DOM does not show the referenced element's contents as children of ‘use’ element.

That implies that the referenced elements children are not accessible by traversing your DOM tree. This also holds true for access via css selectors as the spec goes on:

CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree because its contents are not part of the formal document structure.

查看更多
我命由我不由天
4楼-- · 2019-08-10 18:17

This actually is a very neat trick http://codepen.io/FWeinb/blog/quick-tip-svg-use-style-two-colors, Fabrice Weinberg here is using fill="currentColor" on the symbol so he can change it later using css.

<svg style="display:none;">
  <symbol id="test">
      <rect x="10" y="10" width="100" height="100" /> 
      <rect x="100" y="10" width="100" height="100" fill="currentColor" /> 
  </symbol>
</svg>

<svg class="icon icon--BlueBlack"><use xlink:href="#test" /></svg>
<svg class="icon icon--BlueGreen"><use xlink:href="#test" /></svg>

and

.icon--BlueBlack{
  fill:blue;
}

.icon--BlueGreen{
  fill:blue;
  color:green;
}
查看更多
登录 后发表回答