Align multiple items in an SVG container

I am trying to write an SVG page where we have an icon, and on the right is dynamic text (the distance between the two is fixed). The icon has a fixed width and height, but the text can vary in width.

Both elements are surrounded by a group, and they should be concentrated there. The group also contains free text, which also has a center.

.-------------------------------------. | | | some text | | | | .----. | | | | blah blah blah blah blah | | `----Β΄ | `-------------------------------------Β΄ .-------------------------------------. | | | some text | | | | .----. | | | | blah blah blah | | `----Β΄ | `-------------------------------------Β΄ 

Can anyone enjoy my ASCII skills ?;)

My approach would be to compile the icon and text into one group, and then to the center of that group. Header text too.

I read that I can focus texts in a group, but I have not found a way to align images or actually groups.

 <g id="MainGroup"> <text id="InfoText" x="90" y="0" width="320" text-anchor="middle" font-size="20" fill="#FFFFFF"/> <gx="90" y="0" width="320" text-anchor="middle"> <image id="UserIcon" x="0" y="25" width="48" height="48"/> <text id="Username" x="58" y="55" font-size="22" fill="#FFFFFF"/> </g> </g> 

How can I do it?

Please note that I am completely new to this SVG material, so I may skip the obvious. If I missed some information, you need to ask for it.

+4
source share
1 answer

There is no alignment in SVG. You will need to use the getBBox method with javascript to get the width of the element you want to center and the width of the container, and then do the centering yourself by setting the x attributes of the contained elements.

Here is an example

 <svg width="320" height="200" onload="go()"> <g id="MainGroup"> <rect stroke="black" width="100%" height="100%" fill="none"/> <text id="InfoText" x="160" y="30" text-anchor="middle" font-size="20" fill="black">some text</text> <g id="SubGroup" text-anchor="left"> <rect id="UserIcon" x="0" y="25" width="48" height="48" fill="red" /> <text id="Username" x="50" y="55" font-size="22" fill="black">blah blah blah</text> </g> <g id="SubGroup2" text-anchor="left"> <rect id="UserIcon" x="0" y="25" width="48" height="48" fill="red" /> <text id="Username" x="50" y="55" font-size="22" fill="black">blah blah blah blah blah</text> </g> </g> <script> function centre(element, y) { element.setAttribute("transform", "translate(" + (320 - element.getBBox().width) / 2 + ", " + y + ")"); } function go() { centre(document.getElementById("SubGroup"), 30); centre(document.getElementById("SubGroup2"), 100); } </script> </svg> 
+1
source

Source: https://habr.com/ru/post/1387014/


All Articles