How to align SVG text with CSS

Posted on December 13, 2018 in
1 min read

This is more a reminder to myself to recall how to align properly (both horizontally and vertically) text elements in SVG space through a couple of CSS properties.

Creating a text tag in SVG usually doesn't produce the expected result:

See the Pen txtsvg01 by Fabio Franchino (@abusedmedia) on CodePen.

You don't see anything, uh?

This is because the default vertical alignment is not centered causing the text to be outside the visible canvas.

There are two specific CSS properties, not very intuitive though, that allow to align properly, both horizontally and vertically, a text element in an SVG canvas.

text{
  text-anchor: middle; /* align center */
  dominant-baseline: middle; /* vertical alignment fix */
}

See the Pen txtsvg02 by Fabio Franchino (@abusedmedia) on CodePen.

Hope this little note helps.