在SVG中对齐文本

71

我尝试创建一个包含线段和简短文本片段(通常为两三个单词)的SVG XML文档。我遇到的主要问题是让文本与线段对齐。

对于水平对齐,我可以使用text-anchor属性中的leftmiddleright值。但我找不到垂直对齐的等效属性;alignment-baseline似乎行不通,因此目前我使用dy="0.5ex"来实现居中对齐。

是否有一种正确的方法可以使文本与其垂直居中或顶部对齐?


17
我认为你的水平假设存在错误。根据http://www.w3.org/TR/SVG/text.html#TextAnchorProperty,`text-anchor`属性允许的取值为`start | middle | end | inherit`,不允许使用"left"和"right"。 - Juve
2个回答

61

原来不需要显式文本路径。Firefox 3仅部分支持垂直对齐标签(请查看此帖子)。同时,似乎只有应用为样式时dominant-baseline才有效,而text-anchor可以是样式或标签属性的一部分。

<path d="M10, 20 L17, 20"
      style="fill:none; color:black; stroke:black; stroke-width:1.00"/>
<text fill="black" font-family="sans-serif" font-size="16"
      x="27" y="20" style="dominant-baseline: central;">
  Vertical
</text>

<path d="M60, 40 L60, 47"
      style="fill:none; color:red; stroke:red; stroke-width:1.00"/>
<text fill="red" font-family="sans-serif" font-size="16"
      x="60" y="70" style="text-anchor: middle;">
  Horizontal
</text>

<path d="M60, 90 L60, 97"
      style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/>
<text fill="blue" font-family="sans-serif" font-size="16"
      x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;">
  Bit of Both
</text>

在 Firefox 中可以正常运行。不幸的是,Inkscape 似乎不能处理 dominant-baseline(或者至少不能以相同的方式处理)。


1
可悲的是,截至2011年11月,Firefox仍然是唯一支持“dominant-baseline”的浏览器。我仍然需要一个<text font-size="12px"><tspan dy="6px">偏移量为字体大小的1/2</tspan></text> - Travis
我想至少Chrome也支持它。 - jjmontes
Safari现在似乎支持它。 - Nathan Villaescusa

2

通过将 alignment-baseline 设置为 centralmiddle 确实可以实现此效果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接