Bar*_*Naz 45 css svg text alignment tspan
我需要在SVG中输出多行文本.为此,我使用以下方案:
<text>
<tspan> First line </tspan>
<tspan> Second line </tspan>
</text>
Run Code Online (Sandbox Code Playgroud)
文本的第一行和第二行可以具有不同数量的字符,这些字符可以动态地改变.我希望第二行出现在第一行下面,并且两个文本都要居中.
我可以让第二条线通过添加出现在第一线下方dy="15"第二<tspan>.
我可以<tspan>通过添加text-anchor="middle"来对齐每个人的文本.
但是如何做那些相对中心的对齐<tspan>呢?
我尝试使用x="0"每个,<tspan>但显然它不起作用,因为每个<tspan>都有不同的宽度,较短的行中的渲染文本向左移动.
有没有办法<tspan>只使用CSS和/或SVG 对齐不同宽度的2 的中心.
hel*_*cha 54
如果你添加text-anchor="middle"到每个 tspan中心,你将使它们居中(你必须删除tspans 之间的空间,否则额外的空间将被视为第一行的一部分,它们将不会完全居中).
例如:
<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>
Run Code Online (Sandbox Code Playgroud)
请参阅:JSFiddle
Imr*_*hio 37
text-anchor='start' 为了正确对齐.
text-anchor='middle' 中间对齐.
text-anchor='end' 左对齐
演示代码:
<svg width="100%" height="230" viewBox="0 0 120 230"
xmlns="http://www.w3.org/2000/svg" version="1.1">
<!-- Materialisation of anchors -->
<path d="M60,15 L60,110 M30,40 L90,40 M30,75 L90,75 M30,110 L90,110" stroke="grey" />
<!-- Anchors in action -->
<text text-anchor="start"
x="60" y="40">This text will align right</text>
<text text-anchor="middle"
x="60" y="75">This text will align middle</text>
<text text-anchor="end"
x="60" y="110">This text will align left</text>
<!-- Materialisation of anchors -->
<circle cx="60" cy="40" r="3" fill="red" />
<circle cx="60" cy="75" r="3" fill="red" />
<circle cx="60" cy="110" r="3" fill="red" />
<style><![CDATA[
text{
font: bold 15px Verdana, Helvetica, Arial, sans-serif;
}
]]></style>
</svg>
Run Code Online (Sandbox Code Playgroud)
在此处阅读有关text-anchor属性的更多信息
水平居中文本的关键点:
1.2 x="50%"
.text-anchor='middle'
在您的情况下,您可以写为:
<svg style="width:100%">
<text y="50">
<tspan x="50%" text-anchor="middle"> First line </tspan>
<tspan x="50%" dy="15" text-anchor="middle"> Second line </tspan>
</text>
</svg>
Run Code Online (Sandbox Code Playgroud)