How to Use SVG Markers for Arrows and Symbols

The SVG <marker> element provides a reusable way to attach graphical symbols, such as arrowheads, circles, or custom icons, directly to the vertices and endpoints of lines, paths, polylines, and polygons. Defined inside a <defs> block, markers are styled once and then referenced dynamically across multiple SVG shapes using attributes like marker-end, marker-start, and marker-mid. This modular approach ensures consistent styling, precise geometric alignment, and automatic orientation along the direction of a path.

Defining a Marker in the <defs> Block

Markers are not rendered directly on the canvas; they are templates stored inside the <defs> element. A basic marker definition contains graphic elements, such as a <path> or <polygon>, and uses specific attributes to control its size and bounding box:

Aligning and Orienting the Marker

Proper positioning requires anchoring the marker symbol precisely to the endpoint of a line:

Attaching Markers to Shapes

Once defined, markers can be attached to <path>, <line>, <polyline>, or <polygon> elements using CSS properties or SVG presentation attributes:

Example Implementation

<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <!-- Define the arrowhead marker -->
    <marker 
      id="arrow" 
      viewBox="0 0 10 10" 
      refX="5" 
      refY="5" 
      markerWidth="6" 
      markerHeight="6" 
      orient="auto-start-reverse">
      <path d="M 0 0 L 10 5 L 0 10 z" fill="black" />
    </marker>
  </defs>

  <!-- Apply the marker to a line -->
  <line 
    x1="20" 
    y1="50" 
    x2="180" 
    y2="50" 
    stroke="black" 
    stroke-width="2" 
    marker-end="url(#arrow)" />
</svg>

In this example, the <marker> creates a triangular path pointing along the X-axis. Setting orient="auto-start-reverse" and applying it via marker-end="url(#arrow)" ensures the arrow automatically aligns with the end of the line.