.search-bar svg { width: 25px; height: 25px; color: red; } .search-button svg { width: 25px; height: 25px; color: red; }
<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>
有人能告诉我如何使用CSS控制svg的颜色吗?我尝试使用不同的类和ID来做这个,但似乎没有任何一个对颜色产生影响。我能够改变大小和位置,但无法改变颜色。我希望能够使用一个单独的ID或类来做到这一点,而不是分别改变圆圈和线条的颜色。
<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>
P粉1619397522023-09-19 10:42:16
给共享属性(例如线条和圆的描边)赋予currentColor
的值,然后您可以通过svg的color
属性(或任何祖先或继承的属性)来控制它:
.search-button svg { width: 25px; height: 25px; color: red; } .search-button svg line,.search-button svg circle{ stroke: currentColor; }
<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>
(这是Font Awesome和其他库在幕后所做的。如果您给height
和width
赋予em
单位的值,您也可以通过后续的font-size
来控制它,这也是继承的)