Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest text inside SVG path

Tags:

html

css

svg

Is it possible to nest text (like a text element) inside an SVG path element?

I am asking because I would like a text balloon to show up when hovering over a path, something like this:

path#mypath:hover text {
    display:block;
}

I would like to avoid using JavaScript, but I understand that may be the only option.

like image 647
tau Avatar asked Mar 05 '14 22:03

tau


People also ask

How do I put text inside an SVG path?

To create SVG text that follows a path you use a <textPath> element in combination with a path you define inside <defs> tags. To refer to the path you'll use an xlink:href attribute on the <textPath> . Note: SVG 2.0 is dropping the xlink: and will simply use href to refer to the path.

Can you insert text in SVG?

SVG treats a text element in much the same way that it treats graphical and shape elements. You position text with x and y coordinates and use fill and stroke options to color text the same way you would with a <circle> or <rect> element.


2 Answers

According to this: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path your can not nest <text> inside <path>

You could however use an adjacent element as the trigger for the hover effect: http://jsfiddle.net/93ufH/1/

<svg>
    <rect x="10" y="10" width="100" height="100"/>
    <text x="0" y="50" font-family="Verdana" font-size="55" fill="blue" > 
        Hello
    </text>
</svg>

CSS

svg text{
    visibility:hidden;
}

svg rect:hover + text{
    visibility:visible;
}
like image 181
Mathias Avatar answered Oct 29 '22 10:10

Mathias


If you want to display tooltip, You can insert title element into target shape element, like this.

<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle r="50" cx="50" cy="50">
        <title>tooltip</title>
    </circle>
</svg>
like image 20
defghi1977 Avatar answered Oct 29 '22 12:10

defghi1977