CSS - 使用类名为SVG填充样式

7

我这里有一个jsfiddle - http://jsfiddle.net/morettmt/v7mx737w/2/

我可以通过样式化分组来更改填充颜色

是否有一种方式可以向SVG添加自己的类,并在CSS中使用它

    .triangle{
        fill: red;
    }

1
为什么不使用.triangle g作为选择器?内部的g填充方式不同。 - Harry
2个回答

7
如果你想在SVG中使用类,你需要像这样做:

.play-triangle>g {
  fill: red;
}
<svg class="play-triangle" width="100px" height="107px" viewBox="0 0 10 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
  <g id="Guide" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
    <g id="Iconography" sketch:type="MSArtboardGroup" transform="translate(-421.000000, -286.000000)">
      <path d="M421.002864,301.137442 C421.001935,301.394293 421.098144,301.651636 421.293405,301.846897 C421.686652,302.240144 422.317878,302.236638 422.709368,301.845148 L429.778687,294.775829 L430.485793,294.068722 L422.709368,286.292297 C422.322784,285.905713 421.68393,285.900024 421.293405,286.290548 C421.086336,286.497617 420.989274,286.77067 421.000938,287.039961 C421.000655,287.049803 421.000512,287.059682 421.000512,287.069594 L421.000512,301.067851 C421.000512,301.091254 421.001305,301.114459 421.002864,301.137442 L421.002864,301.137442 L421.002864,301.137442 Z"
        id="Rectangle-78" sketch:type="MSShapeGroup"></path>
    </g>
  </g>
</svg>


3

您的问题是,您class样式中的颜色被子元素<g>上显式设置的fill覆盖了。如果您删除它,您的CSS将会生效。

.triangle{
 fill: red;
}
<svg width="100px" height="107px" viewBox="0 0 10 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
     
     <g class="triangle" id="Guide" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
         <g id="Iconography" sketch:type="MSArtboardGroup" transform="translate(-421.000000, -286.000000)">
             <path d="M421.002864,301.137442 C421.001935,301.394293 421.098144,301.651636 421.293405,301.846897 C421.686652,302.240144 422.317878,302.236638 422.709368,301.845148 L429.778687,294.775829 L430.485793,294.068722 L422.709368,286.292297 C422.322784,285.905713 421.68393,285.900024 421.293405,286.290548 C421.086336,286.497617 420.989274,286.77067 421.000938,287.039961 C421.000655,287.049803 421.000512,287.059682 421.000512,287.069594 L421.000512,301.067851 C421.000512,301.091254 421.001305,301.114459 421.002864,301.137442 L421.002864,301.137442 L421.002864,301.137442 Z" id="Rectangle-78" sketch:type="MSShapeGroup"></path>
         </g>
     </g>
 </svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接