SVG
The element of SVG (Scalable Vector Graphics) is used to draw rectangles; it is one of the commonly used basic shapes in SVG. It lets you draw rectangles and control the position, size, rounded corners, and other styles by setting attributes.
Basic Syntax
y="y-coordinate"
width="width-value"
height="height-value"
rx="rx-value"
ry="ry-value"
fill="fill-color"
stroke="stroke-color"
stroke-width="width-value"
/>
Attribute Analysis:
-
xandyThe attribute specifies the coordinates of the top-left corner of the rectangle, i.e., the starting point of the rectangle. -
widthandheightThe attribute defines the width and height of the rectangle. -
rxandryThe attribute is used to specify the corner radius of the rectangle. If onlyrxis set, all corners have the same radius; if bothrxandryare set, you can specify the horizontal and vertical corner radii separately. -
fillThe attribute defines the fill color of the rectangle. -
strokeThe attribute defines the stroke color of the rectangle. -
stroke-widthThe attribute defines the stroke width of the rectangle.
The following code draws a rectangle with blue fill, black stroke, and a width of 2 pixels; the top-left corner is at (50, 50), the width is 100, and the height is 80.
Example 1
Below is the SVG code:
Example
Try it »
Click to view: View SVG File.
Code analysis:
- The width and height attributes of the rect element define the height and width of the rectangle
- The style attribute is used to define CSS properties
- The CSS fill property defines the fill color of the rectangle (rgb value, color name, or hexadecimal value)
- The CSS stroke-width property defines the width of the rectangle border
- The CSS stroke property defines the color of the rectangle border
Example 2
Let's look at another example that contains some new attributes:
Example
Try it »
Click to view: View the SVG file.
Code analysis:
- The x attribute defines the left position of the rectangle (for example, x="0" defines that the rectangle's distance to the left of the browser window is 0px)
- The y attribute defines the top position of the rectangle (for example, y="0" defines that the rectangle's distance to the top of the browser window is 0px)
- The CSS fill-opacity property defines the transparency of the fill color (valid range: 0 - 1)
- The CSS stroke-opacity property defines the transparency of the outline color (valid range: 0 - 1)
Example 3
Define the opacity of the entire element:
Below is the SVG code:
Example
Try it »
For Opera users:View the SVG file.
- The CSS opacity property is used to define the transparency of an element (range: 0 to 1).
Example 4
The last example, creating a rectangle with rounded corners:
Below is the SVG code:
Example
Try it »
For Opera users:View the SVG file.
- The rx and ry attributes make a rectangle have rounded corners.