.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
來控制它,這也是繼承的)