将文本行对齐到SVG的中心 [英] Align lines of text to center in SVG

查看:116
本文介绍了将文本行对齐到SVG的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在SVG中输出多行文本。为此,我正在使用以下方案:

 < text> 
< tspan>第一行< / tspan>
< tspan>第二行< / tspan>
< / text>

文本的第一行和第二行可以具有不同数量的字符,可以动态更改。
我希望第二行显示在第一行下方,并且两个文本都居中。



我可以使第二行显示在第一行下方通过为第二个< tspan> 添加 dy = 15



我可以通过添加 text-anchor = middle < tspan> 中的文本



但是如何处理< tspan> 的相对中心对齐呢?



我尝试对每个< tspan> <都使用 x = 0 ,但显然不起作用,因为每个< tspan> 具有不同的宽度,并且较短行中的呈现文本向左移动。 / p>

是否可以仅使用CSS和/来对齐2个宽度不同的< tspan> 的中心或SVG。

解决方案

如果添加 text-anchor = middle 每个 tspan ,您将它们居中(您还必须删除tspan之间的 空间,否则多余的空间将被视为第一行的一部分,并且它们不会完全居中。)



例如:

 < svg> 
< text y = 50 transform = translate(100)>
< tspan x = 0 text-anchor = middle&0000; 000012340000< / tspan>< tspan x = 0 text-anchor = middle dy = 15> 1234< / tspan>
< / text>
< / svg>

请参阅: JSFiddle


I need to output multiple lines of text in SVG. For that I'm using the following scheme:

<text>
  <tspan> First line </tspan>
  <tspan> Second line </tspan>
</text>

First and second line of the text can have different number of characters, which can change dynamically. I want the second line to appear under the first line and text in both of them to be centered.

I can make second line appear below the first line by adding dy="15" for the second <tspan>.

I can align the text in each individual <tspan> by adding text-anchor="middle" to it.

But how to do relative centric alignment of those <tspan>'s?

I tried to use x="0" for each <tspan> but apparently it doesn't work since each <tspan> has different width and the rendered text in the shorter line is shifted to the left.

Is there a way to align centres of 2 <tspan>'s of different width using only CSS and/or SVG.

解决方案

If you add text-anchor="middle" to each tspan you will center them (you have to remove the space between the tspans as well, otherwise the extra space will be considered as part of the first line and they won't be completely centered).

For example:

<svg>
    <text y="50" transform="translate(100)">
       <tspan x="0" text-anchor="middle">000012340000</tspan><tspan x="0" text-anchor="middle" dy="15">1234</tspan>
   </text>
</svg>

See: JSFiddle

这篇关于将文本行对齐到SVG的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆