SVG <rect>
- Previous Page Embed SVG in HTML
- Next Page SVG Circle
SVG Shapes
SVG has some predefined shape elements available for developers to use:
- Rectangle
<rect>
- Circle
<circle>
- Ellipse
<ellipse>
- Line
<line>
- Polyline
<polyline>
- Polygon
<polygon>
- Path
<path>
The following chapters will start with the rect element and explain each element.
SVG Rectangle - <rect>
Example 1
<rect>
The element is used to create rectangles and variants of rectangular shapes:
This is the SVG code:
<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>
Code Explanation:
- The width and height attributes of the <rect> element define the height and width of the rectangle
- The style attribute is used to define the CSS properties of the rectangle
- The CSS fill property defines the fill color of the rectangle
- The CSS border-width property defines the border width of the rectangle
- The CSS stroke property defines the border color of the rectangle
Example 2
Let's look at another example with new properties:
This is the SVG code:
<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>
Code Explanation:
- The x attribute defines the left position of the rectangle (for example, x="50" places the rectangle 50 px from the left margin)
- The y attribute defines the top position of the rectangle (for example, y="20" places the rectangle 20 px from the top margin)
- The CSS fill-opacity property defines the opacity of the fill color (valid range: 0 to 1)
- The CSS border-opacity property defines the opacity of the stroke color (valid range: 0 to 1)
Example 3
It defines the opacity of the entire element:
This is the SVG code:
<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>
Code Explanation:
- The CSS opacity property defines the opacity value of the entire element (valid range: 0 to 1)
Example 4
The last example, creating a rectangle with rounded corners:
This is the SVG code:
<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>
Code Explanation:
- The rx and ry properties make the corners of the rectangle rounded
- Previous Page Embed SVG in HTML
- Next Page SVG Circle