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

Published June 18, 2021

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>

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>

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>

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter