SVG Line

Learn how the <line> element draws a single straight segment between two points using the x1, y1, x2, and y2 coordinate attributes.

The <line> Element

The <line> element is one of the simplest SVG shapes: it draws a straight segment between a starting point and an ending point. Because a line has no interior area, only stroke-related attributes affect how it looks -- fill has no visible effect on a line.

Understanding x1, y1, x2, y2

Every <line> is defined by four required attributes: x1 and y1 set the coordinates of the starting point, while x2 and y2 set the coordinates of the ending point. These coordinates live in the SVG's user coordinate system, where (0,0) is the top-left corner and values increase to the right and downward.

Example: A Basic Line

<!DOCTYPE html>
<html>
<body>

<svg width="200" height="200" viewBox="0 0 200 200">
  <line x1="20" y1="20" x2="180" y2="180" stroke="#2563eb" stroke-width="4" />
</svg>

</body>
</html>

Styling Lines with Stroke Attributes

Because <line> has no fill, you control its appearance almost entirely through stroke properties. stroke sets the color, stroke-width sets the thickness, stroke-linecap shapes the ends (butt, round, or square), and stroke-dasharray turns a solid line into a dashed or dotted pattern.

  • stroke - sets the line color
  • stroke-width - sets the line thickness in user units
  • stroke-linecap - shapes the line ends: butt, round, or square
  • stroke-dasharray - creates dashed or dotted patterns
  • stroke-opacity - controls the transparency of the stroke

Example: Dashed Line with Rounded Caps

<!DOCTYPE html>
<html>
<body>

<svg width="220" height="100" viewBox="0 0 220 100">
  <line x1="10" y1="50" x2="210" y2="50"
        stroke="#f97316" stroke-width="8"
        stroke-linecap="round" stroke-dasharray="12 10" />
</svg>

</body>
</html>
Note: Setting fill="red" on a <line> element has no effect, since a line has zero width and no interior region to fill. Only stroke properties change how it renders.

Example: Lines as Chart Axes

<!DOCTYPE html>
<html>
<body>

<svg width="220" height="180" viewBox="0 0 220 180">
  <line x1="30" y1="10" x2="30" y2="150" stroke="#334155" stroke-width="2" />
  <line x1="30" y1="150" x2="200" y2="150" stroke="#334155" stroke-width="2" />
  <line x1="30" y1="110" x2="200" y2="110" stroke="#e2e8f0" stroke-width="1" />
  <line x1="30" y1="70" x2="200" y2="70" stroke="#e2e8f0" stroke-width="1" />
</svg>

</body>
</html>
Note: The SVG coordinate system starts at (0,0) in the top-left corner. The y-axis increases downward, which is the opposite of the math graphs you may be used to -- a larger y2 value draws further down the page, not up.

Exercise: SVG Line

Which attributes define the two endpoints of a <line> element?