center text in SVG shapes

Spread the love

Whenever you place text inside any SVG shape (rectangle, ellipse, circle etc), you would like to center text in SVG shape. In HTML placing a text relative to parent can be easily done using “text-align: center” property, similarly you can place text center of SVG shape with help of “text-anchor: middle”.  For SVG, it is not that straight forward but i will explain below, how you can achieve it.

Let’s first of all create an svg tag as follow:

Now lets add a <g> tag inside svg to group multiple tag inside.

Now let’s add a circle and text tag inside <g> tag.

See the Pen SVG circle with text by Techhysahil (@techhysahil) on CodePen.

Next thing we need to do is to add transform to  <g> tag, so that all tag inside <g> can be positioned relative to it.

See the Pen SVG element grouped realtive to by Techhysahil (@techhysahil) on CodePen.

Horizontally center:

As seen above, we had placed circle as well text relative to parent <g> position. Now finally you need to add text-anchor=”middle” property to text node which will make it horizontally center position to circle.

See the Pen horizontal center align text inside circle by Techhysahil (@techhysahil) on CodePen.

Vertical center:

Now text is horizontally center aligned but if you also want to make it vertical center, add alignment-baseline=”middle” as pointed out in one of  d3  js docs.


See the Pen horizontal and vertical center text in SVG by Techhysahil (@techhysahil) on CodePen.

Leave a Reply

Your email address will not be published. Required fields are marked *