Centering elements of an SVG

2

Hello, I have <g> inside an SVG and would like to centralize your content, basically it would look like this:

+-----------------+       x-----------------+
|  X              |       |                 |
|                 |       |                 |
|                 |       |                 |
|                 | ----> |        x        |
|                 |       |                 |
|                 |       |                 |
|                 |       |                 |
+-----------------+       +-----------------+

Can you help me?

Help Code

<g id="content" transform="translate(28.000000, 50.000000)">
    <text id="header" font-family="Varela Rounded, sans-serif" fill="#334152">
        <tspan x="65" y="35" font-weight="bold" font-size="16">COMPROVANTE</tspan>
        <tspan x="174" y="2" opacity="0.8" font-size="10">
            {{transacao?.registered | date:'dd.MM.yyy'}} | {{ transacao?.registered | date :'HH:mm'}}
        </tspan>
    </text>
<g>

In case I would like to center this <text> within <g>

    
asked by anonymous 13.11.2018 / 20:01

1 answer

1

I'll give you a step by step that will help you. Detail your tag <g> is not closed correctly must be </g>

1 - Align <g> in the center of SVG using transform="translate(201, 151)" note that values 201 and 151 are the approximate center of viewbox of SVG that in your case is viewBox="0 0 403 302"

2 - Align text in the center of the axis using% s of SVG itself link This will make the text always centered regardless of the number of characters.

3 - Set the subtitle's Y value to be below the main text text-anchor="middle"

OBS: I just put a border in SVG so you can better visualize how the centering was done:

svg {
    border:1px solid;
}
<svg width="403" height="302" viewBox="0 0 403 302" fill="none" xmlns="http://www.w3.org/2000/svg">
    <g id="content" transform="translate(201, 151)">
        <text text-anchor="middle" id="header" font-family="Varela Rounded, sans-serif" fill="#334152">
            <tspan x="0" y="0" font-weight="bold" font-size="16">COMPROVANTE</tspan>
            <tspan x="0" y="15" opacity="0.8" font-size="10">
                texto dinâmico
            </tspan>
        </text>
    </g>
</svg>
    
14.11.2018 / 15:52