Sijia Xiao Sijia Xiao - 4 months ago 9
CSS Question

css doesn't work when applying to rectangle class?

I cannot figure out why the style doesn't apply to rectangle.

style

<style>
.bar {
width: 100;
height: 100;
fill: green;
}

</style>


svg

<body>
<svg width="100" height="100">
<rect class="bar"/>
</svg>
</body>


when I change according to joe_young's suggestions, it works in Chrome but not in Firefox:

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<style>
.bar {
width: 100px;
height: 100px;
fill: green;
}
</style>
</head>



<body>
<svg width="100" height="100">
<rect class="bar" />
</svg>
</body>
</html>

Answer

As for your problem, turns out that firefox doesn't like the SVG's styles in the <style> tags, you need to inline them:

<svg width="100" height="100">
  <rect class="bar" width="100" height="100px" style="fill: green"/>
</svg>

You're trying to use an SVG element, <rect>, so it needs to go within the <svg> tags
Also, when using it with CSS (as you're doing here), your width and height values need a unit, here px

.bar {
  width: 100px;   /* You need to include the 'px' here'*/
  height: 100px;
  fill: green;
}
<svg width="100" height="100">
  <rect class="bar" />
</svg>

Comments