📜  CSS | stroke-dashoffset 属性(1)

📅  最后修改于: 2023-12-03 15:00:06.601000             🧑  作者: Mango

CSS | stroke-dashoffset 属性

The stroke-dashoffset property is used to specify the distance between the start of a dash pattern and the start of a path. It is used in conjunction with the stroke-dasharray property to create dashed or dotted lines.

Syntax
stroke-dashoffset: <length> | <percentage> | inherit;

where <length> can be a value in pixels, points, ems, or other CSS length units, and <percentage> can be a percentage value.

Values
  • <length>: Specifies a fixed distance in units such as pixels, points, ems, or other CSS length units.
  • <percentage>: Specifies a distance as a percentage of the length of the path.
  • inherit: Inherits the value from the parent element.
Example

Suppose you have an SVG path element like this:

<svg viewBox="0 0 100 100">
  <path d="M 10 50 L 90 50" stroke="black" stroke-width="5" />
</svg>

We can create a dashed line by setting both stroke-dasharray and stroke-dashoffset:

path {
  stroke-dasharray: 10;
  stroke-dashoffset: 0;
}

The stroke-dasharray property specifies the length of each dash and gap in the pattern. In this case, there is only one dash of length 10, followed by a gap of the same length.

By default, the dash pattern starts at the beginning of the path. However, we can use the stroke-dashoffset property to shift the pattern by a distance of our choosing:

path {
  stroke-dasharray: 10;
  stroke-dashoffset: -5;
}

This will create the same dashed line, but shifted 5 units to the left.

Conclusion

The stroke-dashoffset property is a powerful tool for creating custom dashed or dotted lines in SVG. By combining it with stroke-dasharray, we can control the length and spacing of the dashes as well as their starting position.