SVG Rectangle

What You’ll Learn
The SVG <rect> element draws rectangles and rounded rectangles. It’s one of the most useful SVG shapes for UI: cards, buttons, backgrounds, badges, and diagram blocks.
You’ll learn the core geometry attributes (x, y, width, height) plus rounded corners with rx/ry, and common styling with fill and stroke.
⚡ Quick Reference — SVG Rect Attributes
x, y
numberTop-left corner coordinates
width, height
numberRectangle size
rx, ry
numberCorner radius (rounded rectangle)
fill
colorInterior colour
stroke
colorOutline colour
stroke-width
numberOutline thickness
Basic Syntax
<svg>
<rect x="50" y="50" width="100" height="80" />
</svg>👀 Live Preview — Sharp vs Rounded
Rounded corners are controlled by rx and ry.
Sharp corners
Rounded (rx=12)
Rounded + stroke
1
Basic Rectangle
A simple rectangle with fill and stroke styling.
index.html
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="80" fill="blue" stroke="black" stroke-width="2" />
</svg>2
Rounded Rectangle (rx/ry)
Rounded corners are controlled by rx and ry. This is common for cards and buttons.
index.html
<svg width="240" height="160" viewBox="0 0 240 160">
<rect x="30" y="40" width="180" height="80" rx="18" ry="18"
fill="#10b981" stroke="#064e3b" stroke-width="3" />
</svg>💡 Best Practices
Do
- Use a
viewBoxif the rectangle must scale responsively - Use
rx/ryfor modern UI shapes (buttons/cards) - Keep stroke widths consistent across a component set
- Use CSS classes for styling if you have many rectangles
- Set
fill="none"if you only want an outline
Don’t
- Set width/height to 0 (nothing will render)
- Place the rectangle outside the viewBox/canvas by accident
- Over-round corners (rx/ry too large for the size)
- Rely on stroke only without setting stroke-width
- Hard-code pixel sizes if the graphic needs to be responsive
❓ Frequently Asked Questions
Use
<rect> with x, y, width, and height. Style with fill and stroke.They control rounded corners. Increase them to make the rectangle look more like a pill or card.
Check that
width and height are not zero, the rectangle is inside the viewBox, and you have either a visible fill or a stroke.Yes. Use CSS selectors to set
fill, stroke, stroke-width, and hover/focus effects.Use a
viewBox on the parent <svg> and size the SVG with CSS so it scales cleanly.Level Up Your Stroke Styling
Next, learn stroke width, caps, joins, and dash patterns for clean SVG design.
4 people found this page helpful
