CSS Basics: stroke-dasharray
CSS, or Cascading Style Sheets, is a fundamental technology used for styling web pages. It allows developers to control the appearance of HTML elements, including their size, color, and layout. One of the lesser-known CSS properties is stroke-dasharray
, which is primarily used to create dashed or dotted lines in SVG (Scalable Vector Graphics) and HTML elements.
Understanding stroke-dasharray
The stroke-dasharray
property defines the pattern of dashes and gaps used to create a dashed or dotted line. It takes a list of values as its input, specifying the length of each dash and gap in the pattern. For example, stroke-dasharray: 5 2
creates a pattern with a dash of length 5 pixels followed by a gap of length 2 pixels.
The values provided to stroke-dasharray
can be in pixels, percentages, or even unitless numbers. When using percentages, the values are relative to the length of the path being stroked. For example, stroke-dasharray: 50% 25%
creates a pattern with a dash of length 50% of the path's length followed by a gap of length 25% of the path's length.
Applying stroke-dasharray to SVG
In SVG, the stroke-dasharray
property is commonly used to style the outlines of shapes and paths. By specifying different dash and gap lengths, developers can create visually appealing effects. For example, a dashed line can be created by setting stroke-dasharray: 5 2
, while a dotted line can be achieved with stroke-dasharray: 1 3
.
Here's an example of how to apply stroke-dasharray
to an SVG path:
<svg width="200" height="200">
<path d="M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80"
stroke="black" stroke-width="2" fill="none"
stroke-dasharray="5 2" />
</svg>
In the above example, the stroke-dasharray
property is set to 5 2
, creating a dashed line effect for the SVG path.
Using stroke-dasharray in HTML elements
While stroke-dasharray
is primarily used in SVG, it can also be applied to HTML elements. By setting the border-style
property to dashed
or dotted
, and specifying the border-width
and border-color
, developers can create dashed or dotted borders.
Here's an example of how to use stroke-dasharray
in an HTML element:
<div style="border-style: dashed; border-width: 2px; border-color: black;
width: 200px; height: 200px; stroke-dasharray: 5 2;">
This is a div with a dashed border.
</div>
In the above example, the stroke-dasharray
property is applied to the div
element, creating a dashed border with a dash of length 5 pixels followed by a gap of length 2 pixels.
Conclusion
The stroke-dasharray
property is a powerful tool for creating dashed or dotted lines in SVG and HTML elements. By specifying the lengths of dashes and gaps, developers can achieve various visual effects. Whether it's styling SVG paths or creating borders for HTML elements, stroke-dasharray
offers flexibility and creativity in web design.
For more information on VPS hosting solutions, visit Server.HK.