Dark Night
Dark Night

Reputation: 511

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

I read somewhere that CSS and SVG don't go together, but CSS clearly works with SVG. 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 change the CSS element to this:

rect:hover{
 fill: blue;
}

Color would NOT change on hover. What is going on? It partially works?

Upvotes: 3

Views: 78

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240858

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).

See this MDN article on CSS specificity.

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 {
  fill: #d64526
}
rect:hover {
  fill: blue;
}
<svg>
  <rect width="300" height="100" />
</svg>

Upvotes: 4

Related Questions