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
widthandheight, which makes the rectangle invisible. - Using negative values for
widthorheight, which is invalid. - Not including the
<svg>container, so the rectangle won't render. - Setting
filltononewithout astroke, 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
| Attribute | Description | Example |
|---|---|---|
| x | Horizontal position of top-left corner | x="20" |
| y | Vertical position of top-left corner | y="30" |
| width | Width of the rectangle | width="150" |
| height | Height of the rectangle | height="100" |
| fill | Fill color inside the rectangle | fill="blue" |
| stroke | Border color | stroke="black" |
| stroke-width | Border thickness | stroke-width="2" |
Key Takeaways
Use the element inside
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