Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to manipulate an external .svg file via CSS.

HTML

<body>
    <div class="mysvg">
    <img src="decho.svg" alt="decho" width="200px"></img>
    </div>
</body>

CSS

div.mysvg img {
    opacity: .3;
    transition: opacity 1s linear 0s;
}
    div.mysvg img:hover {
    opacity: 1;
}

This code works for opacity, but not for fill or other svg specific attributes like stroke. I am aware I can't do that with an img tag, but I've been looking for hours and I can't find the correct way to do it with svg or object.

So basically, my questions is, how do I achieve the same result as the code which I linked, but to be able to manipulate fill, stroke etc. properties and it must be an external file, not just an inline svg code pasted in the html.

If someone is able to show me the correct way to do it, I'd be most grateful. Thanks.


EDIT:

I managed to do it by adding a css inside the .svg file itself. It must be right after the svg opening tag.

<svg ...>
<style type="text/css" media="screen">  
    <![CDATA[  
    g {  
        fill: yellow;  
        stroke: black;  
        stroke-width: 1;
        transition: fill 1s linear 0s;
    }
    g:hover {
        fill: blue;
    }
    ]]>  
</style> 
<g>
    <path ...>
</g>
</svg>

You also need to insert it as an object in the html, otherwise it won't work.

<object data="decho.svg" type="image/svg+xml">

Hopefully this helps to someone looking for an answer like mine in future. This is what helped me http://www.hongkiat.com/blog/scalable-vector-graphic-css-styling/.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is in my opinion the greatest flaw in svg: sandboxing.

Svg files are sandboxed: in their own document, which is why a typical 'fill:' style will not apply. Likewise, the css you write in your svg will not apply to the rest of your site.

Adding css directly to an svg: Not a good solution as you will end up rewriting the css in every svg you use.

The real solution: An "icon-system". Svg font-face or svg sprites. Read more about them here.

The reason opacity works: Opacity applies to the svg object/frame itself, not the contents of the svg (which are inaccessible).

I should also note that no matter how you load those svg's, inline, by reference, in an object, as a background, you will not be able to get inside the sandbox. This is why converting them to a font or using sprites is necessary for using hover, focus, and other effects/transitions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...