问题
Issue 1
I'm trying to change the stroke color of an inline svg on hover. It's a path exported from Illustrator and put through Peter Collingridge's SVG optimiser. The articles I read on styling inline SVG are very straight forward but the techniques won't work on my SVG.
I have placed a hover pseudo-class on the tag and can't seem to target the stroke.
<svg class="highlight" width="86" height="68" viewBox="0 0 85.7 68.5">
<polygon points="11 60.7 74.7 60.7 42.8 4.4 " style="fill:none;stroke-width:3;stroke:#491EC4"/>
</svg>
I set the background-color to pink to check that hover is working and that's fine.
.highlight:hover {
background-color: pink;
stroke: red;
}
Here it is on jsfiddle.
I also tried to wrap the polygon in a use tag with an id to change the stroke in CSS as well as adding the svg selector with stroke:inherit, as suggested in a Codrops article. Also, jQuery's hover method with no luck.
What am I doing wrong and why are these three techniques not working?
Issue 2
Sublime Text 2 won't recognise the stroke property. It comes up white when I type it in CSS and HTML. Does this mean it's invalid? I looked at the README file for a CSS3 plugin to see what it's adding and there's no "stroke" property. Should I be using Sublime Text 3 in beta?
All these things...
回答1:
The CSS in the SVG is inline CSS and so is being applied after your stylsheet and thus is overriding it.
The simplest solution is to xxtract the CSS from the SVG and put it all in your stylesheet.
.highlight {
fill: none;
stroke-width: 3;
stroke: #491EC4;
}
.highlight:hover {
/* background-color: pink; */
stroke: red;
}
<svg class="highlight" width="86" height="68" viewBox="0 0 85.7 68.5">
<polygon points="11 60.7 74.7 60.7 42.8 4.4 " />
</svg>
回答2:
the style property in your html overwrite your css selectors. So include all your style properties in the css.
Check the jsfiddle link ;)
https://jsfiddle.net/ojn8r810/3/
HTML
<svg class="highlight" width="86" height="68" viewBox="0 0 85.7 68.5">
<polygon points="11 60.7 74.7 60.7 42.8 4.4 "/>
</svg>
CSS
.highlight {
fill:none;
stroke-width:3px;
stroke:#491EC4;
}
.highlight:hover {
background-color: pink;
stroke: red;
}
回答3:
You'll need to select the polygon tag, since that tag is styled to have a stroke.
Since it's been decorated with an inline style, your css rule should use !important
in order to override the inline style.
.highlight:hover {
background-color: pink;
}
.highlight:hover polygon{
stroke: red !important;
}
<svg class="highlight" width="86" height="68" viewBox="0 0 85.7 68.5">
<polygon points="11 60.7 74.7 60.7 42.8 4.4 " style="fill:none;stroke-width:3;stroke:#491EC4"/>
</svg>
Disclaimer: It would be preferable to extract the inline styles and move them to their own css files (as mentioned by Paulie_D). If by any means extracting is not possible, you could go with !important
来源:https://stackoverflow.com/questions/37940282/changing-the-stroke-color-for-an-inline-svg