css 更改svg颜色

有些时候我们也许会使用css直接操控svg,svg可以像jpg,png那样以图片形式使用,也可以直接以标签形式使用。前者不可以设置颜色,而后者可以。

示例

这是一段svg代码

<svg width="8px" height="12px" viewBox="0 0 8 12" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

    <!-- Generator: Sketch 47.1 (45422) - http://www.bohemiancoding.com/sketch -->

    <title>Rectangle 8 Copy 10</title>

    <desc>Created with Sketch.</desc>

    <defs></defs>

    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round">

        <polyline id="Rectangle-8-Copy-10" stroke="#8F99AE" stroke-width="2" transform="translate(2.242641, 6.242641) scale(1, -1) rotate(-135.000000) translate(-2.242641, -6.242641) " points="5.24264069 9.24264069 -0.757359313 9.24264069 -0.757359313 3.24264069 -0.757359313 3.24264069"></polyline>

    </g>

</svg>

React中使用为例

此时,只需要从svg标签部分开始引用即可,注意,react中不支持命名空间写法xmlns:xlink,要写成xmlnsXlink,短横也是如此。

<svg width="8px" height="12px" viewBox="0 0 8 12" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">

    <g id="Page-1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd" strokeLinecap="round" strokeLinejoin="round">

        <polyline id="Rectangle-8-Copy-10" stroke={"#8F99AE"} strokeWidth="2" transform="translate(2.242641, 6.242641) scale(1, -1) rotate(-135.000000) translate(-2.242641, -6.242641) " points="5.24264069 9.24264069 -0.757359313 9.24264069 -0.757359313 3.24264069 -0.757359313 3.24264069"></polyline>

    </g>

</svg>

更改颜色

  • 只需要用css 选择器选中polyline 标签的stroke属性即可,可以把这个当color用

 svg g polyline {

    stroke: red;

}

hover效果

  • 有时候我们会添加hover效果,大多数情况下,是具有父子关系的盒子,代码如下

.father:hover svg g polyline {

    stroke: red;

}

发表回复

© 2023 狸玖技术站 - 基于 WordPress