SVG Rectangles
The rect element is used to draw rectangles and squares in SVG. You already saw it briefly in the previous lesson. Here we'll explore it in full detail.
The rect Element
A rect element requires four core attributes to define its position and size:
x: The x-coordinate of the top-left corner of the rectangle.y: The y-coordinate of the top-left corner of the rectangle.width: The width of the rectangle.height: The height of the rectangle.
To draw a square, simply set width and height to the same value.
Basic Rectangles
Here are two rectangles side by side. The first uses the default sharp corners, and the second has soft rounded corners using rx and ry.
Rounded Corners: rx and ry
SVG rectangles can have their corners rounded using the rx and ry attributes. These define the horizontal and vertical radius of the corner ellipses respectively.
rx: The horizontal radius of the corner rounding.ry: The vertical radius of the corner rounding.
If you only specify one of them, the other will automatically inherit the same value. Setting rx="50%" and ry="50%" on a square will even produce a perfect circle.
Using Strokes
You can add a border (called a stroke) to any rect using the stroke and stroke-width presentation attributes. Setting fill="none" will produce an outlined-only rectangle.
You can also create dashed borders using the stroke-dasharray attribute, which takes a comma-separated list of dash and gap lengths.
The rect Attributes Summary
| Attribute | Description |
|---|---|
x |
X-coordinate of the top-left corner. Default is 0. |
y |
Y-coordinate of the top-left corner. Default is 0. |
width |
Width of the rectangle. Required. |
height |
Height of the rectangle. Required. |
rx |
Horizontal corner radius for rounding. |
ry |
Vertical corner radius for rounding. |
fill |
Fill color of the rectangle. Default is black. |
stroke |
Outline (border) color. |
stroke-width |
Thickness of the outline. |
stroke-dasharray |
Pattern of dashes and gaps for the outline. |