How to create or draw a rectangle using SVG in HTML?

Published June 15, 2021

To create a rectangle, you can use the rect element inside the svg element in HTML.

TL;DR

<!-- Create rectangle in SVG -->
<svg>
  <rect x="0" y="0" width="30" height="20" />
</svg>

For example, to make a 30*20 (width and height) rectangle, first we can define the rect element inside the svg element like this,

<!-- Create rectangle in SVG -->
<svg>
  <rect />
</svg>

But this alone wouldn't show anything on the screen since it doesn't know how to draw the rectangle on the screen. For that we have to set some attributes on the rect element like:

  • the x attribute, which tells where to start drawing in the x-axis. It is called the x-coordinate.
  • the y attribute, which tells where to start drawing in the y-axis. It is called the y-coordinate.
  • the width attribute, to define the width for the rectangle in our case it is 30px.
  • the height attribute, to define the height for the rectangle in our case it is 20px.

So it may look like this,

<!-- Create rectangle in SVG -->
<svg>
  <rect x="0" y="0" width="30" height="20" />
</svg>

So in the end, we will have a rectangle drawn to the screen like this,

And we have drawn a rectangle successfully using SVG in HTML. Yay 🎊!

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter