I just want to change the svg fill color and hover color. But I saw this svg attached like this:
<use xlink:href="#search-magnify"></use>
I think it's referring to this svg somewhere from the website. I just want to change the fill color without editing the original svg. So I tried wrapping it on span with class and style this way.
.icon svg path{
fill: red;
color: red;
}
But it's not working at all. Here is the fiddle.
What am I missing here? Can this not be achieved by css?
If you are not in control of your SVG, (perhaps because it comes from an external source you are re-theming,) you are stuck using ! important to override the SVG fill property. If your SVG is in your code base, it is much better to set fill="currentColor" , and then set the CSS color property. Save this answer.
Edit your SVG file, add fill="currentColor" to svg tag and make sure to remove any other fill property from the file. Note that currentColor is a keyword (not a fixed color in use). After that, you can change the color using CSS, by setting the color property of the element or from it's parent.
When using the <use>
command, SVG elements fall into the shadow DOM
Read the article:
Styling SVG Content with CSS by Sara Soueidan
The Shadow DOM is similar to the normal DOM except that, instead of being part of the main document subtree, nodes in the Shadow DOM belong to a document fragment which is basically just another subtree of nodes which are not as vulnerable to scripts and styles as normal DOM nodes are. This gives authors a way to encapsulate and scope styles and scripts when creating modular components. If you’ve ever used the HTML5 video element or the range input type and wondered where the video controls or range slider components came from, then you’ve already come across the Shadow DOM before.
Therefore, add color inheritance for path
.icon svg path {
fill: inherit;
}
use.sm {
fill: red;
}
Below is the full code
.icon svg path {
fill: inherit;
}
use.sm {
fill: red;
}
<svg version="1.1" id="search-magnify" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" width="30%" height="30%" viewBox="0 0 57 57" style="enable-background:new 0 0 57 57;" xml:space="preserve">
<path class="st4" d="M55.1,51.9L41.6,37.8C45.1,33.6,47,28.4,47,23C47,10.3,36.7,0,24,0S1,10.3,1,23s10.3,23,23,23 c4.8,0,9.3-1.4,13.2-4.2L50.8,56c0.6,0.6,1.3,0.9,2.2,0.9c0.8,0,1.5-0.3,2.1-0.8C56.3,55,56.3,53.1,55.1,51.9z M24,6 c9.4,0,17,7.6,17,17s-7.6,17-17,17S7,32.4,7,23S14.6,6,24,6z">
</path>
</svg>
<span class="icon">
<svg class="icon-svg svg-search" width="15%" height="15%">
<use class="sm" xlink:href="#search-magnify"></use>
</svg>
</span>
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With