Can I use CSS with SVG, or can I only use partially?

I read somewhere that CSS and SVG do not go together, but CSS clearly works with SVG. Take a look at this example:

<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 changed the CSS element to this:

rect:hover{
 fill: blue;
}

Color will not change on hover. What's happening? Does it partially work?

+4
source share
1 answer

What's happening? Does it partially work?

The inline style (added through the attribute style) is more defined, which means that it overrides the color that is added on hover. Inline styles added to an element will always overwrite any styles in CSS (if you are not using !important, which should always be avoided).

. MDN CSS.

rect, , , rect:hover specificity rect, , .

rect {
  fill: #d64526
}
rect:hover {
  fill: blue;
}
<svg>
  <rect width="300" height="100" />
</svg>
Hide result
+4

Source: https://habr.com/ru/post/1623832/


All Articles