Tutorials References Menu

SVG <rect>


SVG Shapes

SVG has some predefined shape elements that can be used by developers:

  • Rectangle <rect>
  • Circle <circle>
  • Ellipse <ellipse>
  • Line <line>
  • Polyline <polyline>
  • Polygon <polygon>
  • Path <path>

The following chapters will explain each element, starting with the rect element.


SVG Rectangle - <rect>

Example 1

The <rect> element is used to create a rectangle and variations of a rectangle shape:

Sorry, your browser does not support inline SVG.

Here is the SVG code:

Example

<svg width="400" height="110">
  <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
Try it Yourself »

Code explanation:

  • The width and height attributes of the <rect> element define the height and the width of the rectangle
  • The style attribute is used to define CSS properties for the rectangle
  • The CSS fill property defines the fill color of the rectangle
  • The CSS stroke-width property defines the width of the border of the rectangle
  • The CSS stroke property defines the color of the border of the rectangle


Example 2

Let's look at another example that contains some new attributes:

Sorry, your browser does not support inline SVG.

Here is the SVG code:

Example

<svg width="400" height="180">
  <rect x="50" y="20" width="150" height="150"
  style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
</svg>
Try it Yourself »

Code explanation:

  • The x attribute defines the left position of the rectangle (e.g. x="50" places the rectangle 50 px from the left margin)
  • The y attribute defines the top position of the rectangle (e.g. y="20" places the rectangle 20 px from the top margin)
  • The CSS fill-opacity property defines the opacity of the fill color (legal range: 0 to 1)
  • The CSS stroke-opacity property defines the opacity of the stroke color (legal range: 0 to 1)

Example 3

Define the opacity for the whole element:

Sorry, your browser does not support inline SVG.

Here is the SVG code:

Example

<svg width="400" height="180">
  <rect x="50" y="20" width="150" height="150"
  style="fill:blue;stroke:pink;stroke-width:5;opacity:0.5" />
</svg>
Try it Yourself »

Code explanation:

  • The CSS opacity property defines the opacity value for the whole element (legal range: 0 to 1)

Example 4

Last example, create a rectangle with rounded corners:

Sorry, your browser does not support inline SVG.

Here is the SVG code:

Example

<svg width="400" height="180">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150"
  style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>
Try it Yourself »

Code explanation:

  • The rx and the ry attributes rounds the corners of the rectangle