Centralize elements of an SVG

Asked

Viewed 1,195 times

2

Hi, I have a <g> within an SVG and would like to center its content, basically it would be 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’d like to centralize this <text> within the <g>

1 answer

2


I’ll give you a step by step that will help you. Detail your tag <g> is not closed properly it has to be </g>

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

2 - Align the text in the center of the axis itself using the text-anchor="middle" of the SVG itself https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor this will cause the text to always be centered independent of the number of characters.

3 - Adjust the Y value of the subtitle to be below the main text y="15"

OBS: I just put a border on the SVG so you can better visualize how the centering turned out:

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.