【发布时间】:2019-05-21 14:11:04
【问题描述】:
目标是垂直和水平对齐一组tspan元素。
但是,父容器不考虑 dy 值。
这会导致对齐问题。
如果您使用此 Codepen 的 dy 值,文本容器的高度始终保持不变:https://codepen.io/anon/pen/WLpvrG?editors=1111。
如何获得 tspan 元素的准确边界矩形?
<svg id="textBox1" class="textBox" x="0%" y="0%" width="100%" height="25%">
<rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
<text class="tspanGroup" x="0" y="0"><tspan x="50%" dy="0em" text-anchor="middle">tspan line 0</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 1</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 2</tspan></text>
</svg>
【问题讨论】:
-
文本容器的高度很好。当您更改 first
tspan元素的dy时,它并不擅长,因为您实际上只是将其向下移动而不是更改其高度。请记住,dy属性表示沿 y 轴移动。它并不表示调整大小。一个简单的解决方法是添加一个不可见的tspan元素作为第一个元素(不要给它任何内容)并使用第二个元素。 -
@icecub 你可以发帖作为答案来获得信用吗?谢谢。
-
@icecub 你还推荐一种更好的方法来垂直/水平居中文本元素吗?感谢您的帮助!
标签: javascript html svg