0

I wanted to center text (two rows) vertically and horizontally inside this circle, but something went wrong:

SVG wrong

SVG wrong preview

I also tried to place a background image in the center, but i would like it to come under the dotted/dashed border layer, not above it. Any suggestion please?

Here is how the text should be, but I want it as text, not as tspan. And of course a centered background image under it.

Good example

1 Answers1

0

If you don't want to use tspan, you'll need two text elements. You can set both elements' coordinates to 50%/50%, and then..

  • To center horizontally on that point, use text-anchor middle.
  • To place the first row just above that point, and the second row just below it, use alignment-baseline baseline/hanging (to get more space between the rows, you'll need to adjust the y coordinates a bit).

Example:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <style>
        text {
            font-family: sans-serif;
            font-size: 30px;
        }
    </style>

    <circle cx="50%" cy="50%" r="45%" stroke="tomato" stroke-width="8" stroke-dasharray="20" fill="none" />
    
    <!-- Anchors in action -->
    <text x="50%" y="50%" text-anchor="middle" alignment-baseline="baseline">First row</text>
    <text x="50%" y="50%" text-anchor="middle" alignment-baseline="hanging">Second row</text>
</svg>

Edit

With more than two lines, it's easier to use one text element with multiple tspan elements. Again, center the text at 50%/50%, and space the tspans evenly using the dy attribyte. Notice how dy is relative to the previous tspan:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <style>
        text {
            font-family: sans-serif;
            font-size: 30px;
        }
        tspan {
            alignment-baseline: central;
        }
    </style>

    <circle cx="50%" cy="50%" r="45%" stroke="tomato" stroke-width="8" stroke-dasharray="20" fill="none" />

    <text x="50%" y="50%" text-anchor="middle">
        <tspan x="50%" dy="-2em">First row</tspan>
        <tspan x="50%" dy="1em">Second row</tspan>
        <tspan x="50%" dy="1em">Third row</tspan>
        <tspan x="50%" dy="1em">Fourth row</tspan>
        <tspan x="50%" dy="1em">Fifth row</tspan>
    </text>
</svg>
Sphinxxx
  • 12,484
  • 4
  • 54
  • 84
  • Thanks, those alignments made it. It works good. Thanks a lot! – Daniel Ilaş Jul 21 '18 at 07:15
  • Still one more question: what if I have 5 lines and want to have them all vertically centered one below the other? – Daniel Ilaş Jul 21 '18 at 08:29
  • @DanielIlaş I've updated my answer with a multi-line solution. Related question: https://stackoverflow.com/questions/31469134/how-to-display-multiple-lines-of-text-in-svg – Sphinxxx Jul 21 '18 at 14:37