How to Add Tooltips to SVG Sub-Elements

Adding tooltips to specific SVG sub-elements, such as paths, circles, or groups, is essential for creating interactive data visualizations, maps, and diagrams. This article outlines the primary methods for implementing SVG tooltips, ranging from lightweight native SVG solutions to fully customizable CSS and JavaScript implementations.

1. The Native SVG <title> Element

The simplest and most accessible way to add a tooltip to an SVG sub-element is by appending a <title> tag directly inside that sub-element.

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="blue">
    <title>This is a native SVG tooltip</title>
  </circle>
</svg>

2. Pure SVG and CSS Hover Elements

You can build custom, stylable tooltips directly inside the SVG document using a combination of SVG <text> and <rect> elements grouped inside a <g> tag, controlled by CSS.

<svg width="200" height="200">
  <g class="tooltip-group">
    <circle cx="100" cy="100" r="50" fill="green" />
    <g class="tooltip-text">
      <rect x="70" y="20" width="60" height="25" fill="#333" rx="4" />
      <text x="100" y="37" fill="#fff" text-anchor="middle" font-size="12">Info</text>
    </g>
  </g>
</svg>
.tooltip-group .tooltip-text {
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
}

.tooltip-group:hover .tooltip-text {
  opacity: 1;
}

3. Absolute-Positioned HTML Div via JavaScript

For fully responsive, HTML-styled tooltips, developers frequently position an HTML <div> over SVG elements using JavaScript event listeners (pointerenter, pointermove, pointerleave).

  1. Create a single, hidden HTML <div> outside the SVG.
  2. Use element.getBoundingClientRect() or event.clientX / event.clientY to calculate coordinates on hover.
  3. Update the tooltip’s top and left CSS properties and toggle visibility.

4. JavaScript Tooltip Libraries

Third-party libraries like Tippy.js (powered by Popper) or D3.js natively support targeting SVG elements.