DEV Community

Cover image for How to create or draw a rectangle using SVG in HTML?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Updated on • Originally published at melvingeorge.me

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

Originally posted here!

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 x-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>
Enter fullscreen mode Exit fullscreen mode

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

svg-rectangle

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


Top comments (0)