Description of the <rect> element

The SVG <rect> element creates a rectangle, as well as rectangle shape variations. It is possible to draw rectangles of various height, width, with different stroke and fill colors, etc. We are going to try some examples.

Example of the SVG <rect> element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <svg width="350" height="120">
      <rect width="250" height="110" style="fill:rgb(53, 153, 0);stroke-width:1;stroke:rgb(32, 33, 49)" />
    </svg>
  </body>
</html>

Now let’s explain this code:

  • The width and height attributes specify the height and the width of the rectangle.
  • The style attribute specifies some CSS properties for the rectangle.
  • The CSS fill property specifies the fill color of the rectangle.
  • The CSS stroke-width property is used to specify the width of the rectangle’s border.
  • The CSS stroke property specifies the color of the rectangle’s border.

Example of the SVG <rect> element with the x and y attributes:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <svg width="400" height="250">
      <rect x="80" y="50" width="180" height="180" style="fill:lightcoral;stroke:purple;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
      Sorry, inline SVG isn't supported by your browser.  
    </svg>
  </body>
</html>

Let’s explain the code above:

  • The x attribute specifies the left position of the rectangle.
  • The y attribute specifies the top position of the rectangle.
  • The CSS fill-opacity property specifies the opacity of the fill color.
  • The CSS stroke-opacity property specifies the opacity of the stroke color.

Example of the SVG <rect> element with the CSS opacity property:

<!DOCTYPE html>
<html>
  <body>
    <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" />
      Sorry, inline SVG is not supported by your browser.  
    </svg>
  </body>
</html>

Example of the SVG <rect> element with the rx and ry attributes:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <svg width="350" height="240">
      <rect x="70" y="50" rx="30" ry="30" width="170" height="170" style="fill:green;stroke:darkgray;stroke-width:5;opacity:0.7" />
      Sorry, inline SVG isn't supported by your browser..
    </svg>
  </body>
</html>

Practice Your Knowledge

What attributes can be specified for SVG rectangles in HTML?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?