Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

svg - text-align="middle" _only_ in y-direction?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...