I've seen a few post here about using dy
to vertically align text, but all of them just pick a random value without explaining it. Surely this value would differ depending on the font size? My text's font size is stored in a variable (fsize
), and its value can change depending on other factors. I tried setting .attr("dy", fsize / 2)
(not quite exactly that since fsize
is a string and in ems, but you get the point), and my text is way off centre. What value should I choose, given a font size of fsize
?
Asked
Active
Viewed 2,698 times
1

Bluefire
- 13,519
- 24
- 74
- 118
-
could you provide an example ? JSFiddle maybe – thatOneGuy Mar 29 '16 at 13:51
-
@thisOneGuy My code's too big for a fiddle, but I can give you a picture if you like. – Bluefire Mar 29 '16 at 13:55
-
Yeah that would be ok maybe – thatOneGuy Mar 29 '16 at 13:58
-
1The `y` attribute of a `text` element specifies the y coordinate of the bottom of the text. The `dx` attribute offsets the text above or below that mark. When you are offsetting by `fsize / 2`, you are offsetting by half of the entire height of the text (the height of a *capital* letter, not lowercase). If you want lowercase text to be centered, you should use `fsize / 4`. – JSBob Mar 29 '16 at 13:59
-
@JSBob My text is numbers, which, I think, are about as high as a capital letter. Anyway, even if they were lowercase, this still doesn't make sense, as my text is waaaay off: http://i.imgur.com/IPVr0tI.png – Bluefire Mar 29 '16 at 14:01
-
OK, so for some reason `fsize / 2` it works perfectly if I set my font size in pixels rather than ems (i.e. `fsize` is a number). Does anyone have any idea why that is? – Bluefire Mar 29 '16 at 14:33
-
Also, don't forget about `alignment-baseline` [css property](http://stackoverflow.com/a/12250444/16363) – Mark Mar 30 '16 at 00:19
1 Answers
4
"Surely this value would differ depending on the font size?"
if you use 'em' units it shouldn't matter what the font size is as they're a relative-size unit
https://www.w3.org/WAI/GL/css2em.htm
So you can use rules of thumb like .attr("dy", "0.7em")
which shifts text y-wards by 70% of the font height

mgraham
- 6,147
- 1
- 21
- 20