DEV Community

Cover image for How to set the background color on the rect svg element in HTML?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to set the background color on the rect svg element in HTML?

Originally posted here!

To set the background color for the rect SVG element, you can use the fill attribute on the rect element inside the svg tag in HTML.

TL;DR

<!-- Set background color on 'rect' svg element -->
<svg>
  <rect x="0" y="0" width="30" height="20" fill="red" />
</svg>
Enter fullscreen mode Exit fullscreen mode

For example to set the color red on the rect svg element, let's use the fill attribute and set its value to the string red like this,

<!-- Set background color on 'rect' svg element -->
<svg>
  <rect fill="red" />
</svg>
Enter fullscreen mode Exit fullscreen mode

But this alone wouldn't show anything on the screen as the browser doesn't know where to start drawing the shape. For that, you also have to add other 4 attributes like the x, y, width, and height. To know more about these attributes check out How to create or draw a rectangle using SVG in HTML?

So at the end it will look like this,

<!-- Set background color on 'rect' svg element -->
<svg>
  <rect x="0" y="0" width="30" height="20" fill="red" />
</svg>
Enter fullscreen mode Exit fullscreen mode

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)