如何通过单一CSS类或ID控制SVG颜色?尺寸可改但颜色无效
问题:用单个类/ID统一控制SVG颜色失败
我能修改SVG的尺寸和位置,但没法通过CSS统一改变它的颜色,试过不同类和ID都没用,不想逐个修改circle和line的颜色,希望靠单个类就能搞定。以下是我尝试的代码:
原CSS代码
.search-bar svg { width: 25px; height: 25px; color: red; } .search-button svg { width: 25px; height: 25px; color: red; }
原HTML代码
<div class="search-bar"> <form> <a class="search-button" type="submit"> <svg class="svg-research" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"> <rect width="256" height="256" fill="none"/> <circle cx="116" cy="116" r="84" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/> <line x1="175.4" y1="175.4" x2="224" y2="224" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/> </svg> </a> </form> </div>
解决方案
问题根源有两个:
- SVG内部的
circle和line写了固定的stroke="#000",内联样式优先级比外部CSS高,直接覆盖了你设置的颜色 - SVG元素默认不会继承父元素的
color属性,需要用currentColor来关联颜色值
步骤1:修改SVG内部的stroke属性
把circle和line里的stroke="#000"改成stroke="currentColor",这样SVG的线条颜色会自动继承自身或父元素的color值:
<div class="search-bar"> <form> <a class="search-button" type="submit"> <svg class="svg-research" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"> <rect width="256" height="256" fill="none"/> <circle cx="116" cy="116" r="84" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/> <line x1="175.4" y1="175.4" x2="224" y2="224" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/> </svg> </a> </form> </div>
步骤2:用单个类控制颜色
现在只需要给SVG的.svg-research类设置color就能统一控制颜色了,CSS可以简化成:
.svg-research { width: 25px; height: 25px; color: red; /* 这个颜色会被SVG的currentColor继承 */ }
如果想通过父元素(比如.search-button)来控制,也可以这么写:
.search-button .svg-research { width: 25px; height: 25px; color: red; }
这样就能通过单个类/ID搞定SVG的颜色控制,不用逐个修改内部元素的stroke属性了。
内容的提问来源于stack exchange,提问作者Thor The dog
相关产品推荐
相关产品推荐

