How to align SVG text with CSS

13th December, 2018 - 1 min. read - in Tutorials - Go to Index

[Hold on] I've made a tool to help people building presentations the modern way.
If you are curious, here the starting point. [/Hold on]

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-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.

Spotted a typo or (likely) a grammar error? Send a pull request.