DEV Community

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

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

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

Originally posted here!

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

TL;DR

<!-- Create square in SVG -->
<svg>
  <rect x="0" y="0" width="30" height="30" />
</svg>
Enter fullscreen mode Exit fullscreen mode

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

<!-- Create square 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 square 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 square in our case it is 30px.
  • the height attribute, to define the height for the square in our case it is 30px.

So it may look like this,

<!-- Create square in SVG -->
<svg>
  <rect x="0" y="0" width="30" height="30" />
</svg>
Enter fullscreen mode Exit fullscreen mode

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

square svg

And we have drawn a square 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)