垂直居中多行SVG文本

时间:2015-06-24 01:47:15

标签: css svg

有人可以给我示例如何在SVG中垂直居中多行文字吗?我用谷歌搜索过,我看到很多对 alignment-baseline dominant-baselin e的引用,但没有具体的例子供我查看。

例如,在下面的SVG中,TEXT元素被其左上角锁定。文本开始出现在该y位置之后。如果我希望文本在y位置的上方和下方均匀分布,我需要做什么?

<text x="110" y="50" dy="0">
   <tspan dy="0em" x="110" style="font-weight: bold; fill: rgb(74, 76, 77);">
     <tspan x="110" dy="0em">This is my long quotation that will now wrap</tspan>
     <tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
     <tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
   </tspan>
   <tspan dy="1.5em" x="110" style="font-style: italic;">
     Speaker, Speaker Description
   </tspan>
</text>

(我通过D3生成这个,如果有帮助的话)

1 个答案:

答案 0 :(得分:0)

您无法真正使用SVG进行自动居中。 SVG没有适当的自动布局。

但是,您可以像使用dy一样,相对于基线定位文本。请记住,dy也可能是否定的。

&#13;
&#13;
<svg width="400" height="150">

  <line x1="110" y1="50" x2="400" y2="50" stroke="red"/>
  <text x="110" y="50">
     <tspan x="110" dy="-0.8em">This is my long quotation that will now wrap</tspan>
     <tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
     <tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
  </text>

</svg>
&#13;
&#13;
&#13;

您可以做的另一件事是使用<foreignObject>元素在您的SVG中嵌入HTML。显然,这只适用于浏览器。