I read somewhere that CSS and SVG don't go together, but CSS clearly works with SVG. Look at this example:
我读到过一些文章,说CSS和SVG不能结合在一起,但是CSS显然可以和SVG一起工作。看看这个例子:
<html>
<head>
<style>
rect:hover{
opacity: 0.5;
}
</style>
</head>
<body>
<svg>
<rect width="300" height="100" style="fill:#d64526" />
</svg>
</body>
</html>
This works, but if I change the CSS element to this:
这是可行的,但是如果我将CSS元素改为:
rect:hover{
fill: blue;
}
Color would NOT change on hover. What is going on? It partially works?
鼠标悬停时颜色不会改变。什么是怎么回事?这部分工作吗?
1 个解决方案
#1
4
What is going on? It partially works?
什么是怎么回事?这部分工作吗?
The inline style (added via the style
attribute) is more specific which means that it is overriding the color that is added on hover. Inline styles added to an element will always overwrite any styles in the CSS (unless you use !important
, which should always be avoided).
内联样式(通过style属性添加)更加具体,这意味着它将覆盖在悬浮上添加的颜色。添加到元素的内联样式总是会覆盖CSS中的任何样式(除非您使用!这很重要,应该始终避免)。
See this MDN article on CSS specificity.
请参阅关于CSS特性的MDN文章。
If you set the initial color using the selector rect
, it would work as expected because rect:hover
has a higher specificity than rect
which means that it will be overridden.
如果您使用选择器rect设置初始颜色,它将按照预期工作,因为rect:hover比rect具有更高的特异性,这意味着它将被覆盖。
rect {
fill: #d64526
}
rect:hover {
fill: blue;
}
<svg>
<rect width="300" height="100" />
</svg>
#1
4
What is going on? It partially works?
什么是怎么回事?这部分工作吗?
The inline style (added via the style
attribute) is more specific which means that it is overriding the color that is added on hover. Inline styles added to an element will always overwrite any styles in the CSS (unless you use !important
, which should always be avoided).
内联样式(通过style属性添加)更加具体,这意味着它将覆盖在悬浮上添加的颜色。添加到元素的内联样式总是会覆盖CSS中的任何样式(除非您使用!这很重要,应该始终避免)。
See this MDN article on CSS specificity.
请参阅关于CSS特性的MDN文章。
If you set the initial color using the selector rect
, it would work as expected because rect:hover
has a higher specificity than rect
which means that it will be overridden.
如果您使用选择器rect设置初始颜色,它将按照预期工作,因为rect:hover比rect具有更高的特异性,这意味着它将被覆盖。
rect {
fill: #d64526
}
rect:hover {
fill: blue;
}
<svg>
<rect width="300" height="100" />
</svg>