Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change both fill and stroke in svg with css

Tags:

css

svg

I have a series of black/transparent SVG icons placed inline in my design. I need to change all black fills AND strokes into a custom color on hover.

I can change the fill attribute with css, however, some of the icons are transparent and thus mostly the strokes need changing. Any ideas how to tackle this? The following doesn't work (it only targets the fill)

.icons svg:hover {
fill:#dd6127;  
stroke:#dd6127;

}

UPDATE: As suggested by Anders G, I was not targeting the svg elements correctly, I solved most of my problems but there are still a few lines that refuse to change color :) Take a look at the fiddle

like image 365
user2135738 Avatar asked Apr 28 '14 21:04

user2135738


People also ask

Can you change color of SVG with CSS?

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.

Can you style SVG with CSS?

Not only does it mean that SVG properties can be styled using CSS as presentation attributes or in style sheets, but this also can be applied to CSS pseudo-classes such as :hover or :active . SVG 2 also introduces more presentation attributes that can be used as styling properties.

How do I change the stroke width in SVG?

You can add a stroke with stroke="black" stroke-width="10" and then adjust your viewBox accordingly. This answer is technically not using CSS.


2 Answers

If you wish to use same color for fill and stroke, "currentColor" value and "color" property are useful.
I mase sample. http://jsfiddle.net/defghi1977/KtCht/1/


svg code using currentColor value.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle fill="none" stroke="currentColor" stroke-width="30" stroke-miterlimit="10" cx="232.083" cy="200.002" r="182.624"/>
    <g>
        <polygon fill="none" stroke="currentColor" points="..."/>
        <polygon fill="currentColor" stroke="currentColor" points="..."/>
    </g>
</svg>

css code using color property.

svg:hover {
    color:#dd6127;  
}
like image 99
defghi1977 Avatar answered Oct 06 '22 09:10

defghi1977


Fiddling a bit in the blind without any code, but my 5 cents say you need to target the SVG elements (inside the SVG). For instance :

.icons svg:hover rect {
    fill:#dd6127;  
    stroke:#dd6127;
}
like image 43
agrm Avatar answered Oct 06 '22 10:10

agrm