Easily center text vertically, with SVG!

3 min read 0 comments
You are browsing the new, beta version of my website. Some things may not work properly. View this page on the old website and if you spot any problems, please file an issue!

These days, we have a number of different ways to vertically align text in a container of variable dimensions:

However, often comes a time when neither is suitable, so here I am, adding yet another option to the list. Of course, it comes with its own set of drawbacks, but there are cases where it might be better than the existing solutions.

It all started when I discovered the text-anchor SVG property. It determines where the x and y attributes on <text> elements refer to. The magic starts when you set it to “middle”, then the x and y attributes refer to the center of the text. So, if you set those to 50%, they refer to the center of the SVG graphic itself, and if you set the SVG width and height to 100%, the text basically sits in the center of the <svg>’s container, which could be any HTML element!

One issue was that this centered the baseline of the text, so I tried to find a way to shift the baseline appropriately. Setting dominant-baseline: middle; on the ```](http://www.w3.org/TR/SVG/text.html#TextElement) element seemed to fix it, but it looks like IE doesn’t support that. I ended up adding [`dy`](http://www.w3.org/TR/SVG/text.html#TextElementDYAttribute)=“.3em” to the [`` element, which fixes it but might need to be adjusted if you change the line-height.

In addition, this method has the following drawbacks I can think of:

However, it has a few advantages too:

You can see and play with the result in the dabblet below:

Verified to work in at least Chrome, Firefox, IE9+. Hope it’s useful, even though it won’t be a good fit in every single use case.