0
0
HtmlHow-ToBeginner · 3 min read

How to Create Rectangle in SVG: Simple Guide with Examples

To create a rectangle in SVG, use the <rect> element inside an <svg> container. Set attributes like x, y, width, and height to define its position and size.
📐

Syntax

The <rect> element draws a rectangle in SVG. Key attributes include:

  • x: The horizontal position of the rectangle's top-left corner.
  • y: The vertical position of the rectangle's top-left corner.
  • width: The rectangle's width.
  • height: The rectangle's height.
  • fill: The fill color inside the rectangle.
  • stroke: The color of the rectangle's border.
  • stroke-width: The thickness of the border.
html
<svg width="200" height="100">
  <rect x="10" y="10" width="100" height="50" fill="blue" stroke="black" stroke-width="2" />
</svg>
Output
A blue rectangle with black border positioned 10 pixels from the top and left inside a 200x100 SVG area.
💻

Example

This example shows a red rectangle with a black border inside an SVG canvas. It demonstrates how to position and size the rectangle.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>SVG Rectangle Example</title>
</head>
<body>
  <svg width="300" height="150" style="border:1px solid #ccc;">
    <rect x="50" y="30" width="200" height="100" fill="red" stroke="black" stroke-width="3" />
  </svg>
</body>
</html>
Output
A red rectangle with a thick black border inside a 300x150 SVG area with a light gray border around the SVG.
⚠️

Common Pitfalls

Common mistakes when creating SVG rectangles include:

  • Forgetting to set width and height, which makes the rectangle invisible.
  • Using negative values for width or height, which is invalid.
  • Not including the <svg> container, so the rectangle won't render.
  • Setting fill to none without a stroke, making the rectangle invisible.

Wrong example:

<svg width="100" height="100">
  <rect x="10" y="10" /> 
</svg>

Corrected example:

<svg width="100" height="100">
  <rect x="10" y="10" width="80" height="50" fill="green" />
</svg>
📊

Quick Reference

AttributeDescriptionExample
xHorizontal position of top-left cornerx="20"
yVertical position of top-left cornery="30"
widthWidth of the rectanglewidth="150"
heightHeight of the rectangleheight="100"
fillFill color inside the rectanglefill="blue"
strokeBorder colorstroke="black"
stroke-widthBorder thicknessstroke-width="2"

Key Takeaways

Use the element inside to create rectangles.
Always set width and height to make the rectangle visible.
Position the rectangle using x and y attributes.
Use fill and stroke to style the rectangle's color and border.
The container is required to display SVG shapes.