SVG Rectangle

Learn how the <rect> element draws rectangles and rounded rectangles using x, y, width, height, and the optional rx/ry corner-radius attributes.

Drawing Rectangles with <rect>

The <rect> element draws a rectangle, and it is one of the most commonly used SVG shapes since it forms the basis for buttons, cards, panels, and bar charts. At minimum it needs a width and a height; without those two attributes, a rectangle has no size and nothing is drawn.

Positioning with x and y

The x and y attributes set the position of the rectangle's top-left corner within the SVG's coordinate system, which places the origin (0, 0) at the top-left of the viewport by default. Both x and y default to 0 if you leave them out, so the rectangle starts flush against the top-left corner.

Rounded Corners with rx and ry

Adding rx rounds the rectangle's corners horizontally, and ry rounds them vertically. If you set only rx, the browser automatically uses the same value for ry, producing evenly rounded corners; setting both to different values produces corners shaped like quarter-ellipses instead of quarter-circles.

  • x and y default to 0 if omitted, placing the rectangle at the top-left corner
  • width and height are required; a rectangle with a zero or missing width/height is not rendered
  • Setting only rx makes ry match it automatically, producing evenly rounded corners
  • Setting different rx and ry values produces corners shaped like quarter-ellipses
  • fill, stroke, and stroke-width work on <rect> exactly as they do on other shapes

Example

<!DOCTYPE html>
<html>
<body>

<svg xmlns='http://www.w3.org/2000/svg' width='200' height='150'>
  <rect x='20' y='20' width='160' height='100' fill='#3b82f6' />
</svg>

</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>

<svg xmlns='http://www.w3.org/2000/svg' width='200' height='150'>
  <rect x='20' y='20' width='160' height='100' fill='#fef9c3' stroke='#ca8a04' stroke-width='5' />
</svg>

</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>

<svg xmlns='http://www.w3.org/2000/svg' width='220' height='100'>
  <rect x='10' y='10' width='200' height='80' rx='20' ry='20' fill='#9333ea' />
</svg>

</body>
</html>
Note: A quick way to build a card or button shape is to draw a <rect> and set rx (and optionally ry) to about 10-20% of the shorter side.
AttributePurpose
xDistance from the left edge of the coordinate system to the rectangle's left side
yDistance from the top edge of the coordinate system to the rectangle's top side
widthHorizontal size of the rectangle
heightVertical size of the rectangle
rxHorizontal radius applied to each corner, rounding the sides
ryVertical radius applied to each corner, rounding the top and bottom

Exercise: SVG Rectangle

Which element draws a rectangle in SVG?