要垂直对齐 SVG 中 text
元素内的 tspan
元素,CSS 属性 alignment-baseline
和 dominant-baseline
分别在 Chrome 和 FF 中运行良好。到目前为止一切顺利。
使用 Internet Explorer 会变得有点疯狂:
- 打开 bug report断言这些属性不适用于 IE9-11 ...
- ... 但是 official documentation表示支持
alignment-baseline
- IE9 和 IE11 中的 CSS 特性嗅探报告说它们支持
alignment-baseline
以及dominant-baseline
fortspan
,但它们不适用于任何值 - 为了让挫败感更加困惑,这 MSDN dev page简单地说这两个属性目前不受支持
这对 IE9 来说不是问题(可以简单地 hack the desired alignment ),但由于我想避开浏览器检测,我想知道:
- 是否有可行的跨浏览器解决方案?
- 为什么连 IE11 都不支持这个基本的 SVG 样式属性?如何解决这个问题?
谢谢!
最佳答案
我不知道为什么 IE 不支持对齐基线,更不用说为什么你会得到这样的混合信息。
您可以使用 dy
属性和基于字体的单位(“em”和“ex”)来破解相同的行为。如果您只想将特定文本元素置于某个点的中心,它会非常有效。
<text x="50%" y="50%" dy="0.5ex" text-anchor="middle">
This text will be centered in your coordinate system!
</text>
但 dy
的问题在于——除非 y
也为同一元素明确设置——它是相对于 计算的前一个字符的位置。因此,如果您想使文本范围相对于周围范围居中,则必须首先调整任何先前的偏移量,然后设置新的偏移量。生成的代码并不漂亮:
<text x="50%" y="25%" font-size="150%">
<tspan dy="0.5ex">Large font with</tspan><tspan
dy="-0.5ex"> <tspan
font-size="50%" dy="0.5ex">small font<tspan
dy="-0.5ex"> </tspan></tspan></tspan><tspan
dy="0.5ex">embedded.</tspan>
</text>
<text x="50%" y="75%" font-size="75%">
<tspan dy="0.5ex">Small font with</tspan><tspan
dy="-0.5ex"> <tspan
font-size="200%" dy="0.5ex">large font<tspan
dy="-0.5ex"> </tspan></tspan></tspan><tspan
dy="0.5ex">embedded.</tspan>
http://fiddle.jshell.net/awj49/
在 IE11 中呈现:
(灰线标出引用y坐标)
如果可以的话,只需在每个 tspan 上显式设置 y
属性即可使代码更简洁:
<text x="50%" font-size="150%">
<tspan y="25%" dy="0.5ex">Large font with</tspan>
<tspan font-size="50%" y="25%" dy="0.5ex">small font</tspan>
<tspan y="25%" dy="0.5ex">embedded.</tspan>
</text>
<text x="50%" y="75%" font-size="75%">
<tspan y="75%" dy="0.5ex">Small font with</tspan>
<tspan font-size="200%" y="75%" dy="0.5ex">large font</tspan>
<tspan y="75%" dy="0.5ex">embedded.</tspan>
</text>
http://fiddle.jshell.net/awj49/1/
最终效果图是一样的:
关于javascript - Internet Explorer 和 tspan 垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513185/