text-align=“middle” _only_ in y-direction?

烂漫一生 提交于 2019-11-28 06:37:27

问题


I can use text-align="middle" on a text element to center text. Actually this only works nice for the x-direction. For the y-direction I use the hack of Ian G in question Aligning text in SVG.

But what can I do, if a want to center a text in the y-direction, but want to left-align the text in x-direction? For example, I have a rect-element and a text-element positioned right of it. The text should be vertically aligned to appear centered in relation to the rect. Therefore I use the text-align="middle" property. But I want to left-align the text in the x-direction (since I want to display it at the right of the rect). That doesn't work, since text-align always applies the both, x and y values.

Actually I am not really happy with the vertical alignment in that way and would prefer something else. But didn't find a better solution yet. (I can't use the dominant-baseline attribute, since I am using Batik, which doesn't support it.) I can't even calculate it myself, since in SVG I have no way to query the ascent/descent/baseline of a font.


回答1:


The baseline-related attributes, as you have discovered, are not universally supported (yet).

One possible solution is to use a method similar to the old CSS trick for vertical centering.

Set the y coord of the text to the vertical centre of the object you want to center on. Then use dy with an em value to adjust the text verically.

<text x="0" y="100" font-family="Verdana" font-size="20pt" dy="0.35em">Some TEXT</text>

The amount of dy won't be 0.5em as you might think because the visual centre of the font won't be exactly half the em height. It will vary from font to font. But once you find a good dy value for a particular font, it should work for any font-size.

Demo here: http://jsfiddle.net/js88W/1/

Try changing the font-size value to confirm it stays centred.



来源:https://stackoverflow.com/questions/19253766/text-align-middle-only-in-y-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!