请注意以下代码段:
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
alignment-baseline = "middle"
text-anchor = "middle">
a
</text>
</svg>
&#13;
Chrome会将该代码段呈现为:
而在FireFox上,这就是结果:
如何以跨浏览器兼容的方式复制此代码段?
答案 0 :(得分:6)
&#34; alignment-baseline &#34; Firefox不支持。 尝试使用属性&#34; 显性基线 &#34;它应该适用于两者(Chrome和Firefox但不适用于IE,见下文)。
看看这个old answer
根据SVG规范,对齐基线仅适用于&#34; tspan&#34;,&#34; textPath&#34;,&#34; tref&#34;和&#34; altGlyph&#34;。我的理解是,它用于抵消来自&#34;文本&#34;对象在他们之上。我认为你所寻找的是显性基线。
适用于Chrome和Firefox,但适用于IE。如果你还想在IE中使用垂直居中的文本,你必须使用这样的工作方式:
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
id = "default-text"
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
alignment-baseline = "middle"
dominant-baseline = "middle"
text-anchor = "middle">
a
</text><script>
window.onload = function() {
var text = document.getElementById("default-text"),
bbox = text.getBBox(),
actualHeight = (4 - bbox.y),
fontSize = parseInt(window.getComputedStyle(text)["fontSize"]),
offsetY = (actualHeight / 2) - (bbox.height - fontSize);
text.setAttribute("transform", "translate(0, " + offsetY + ")");
}
</script>
答案 1 :(得分:3)
最简单的跨浏览器解决方案就是将dy
属性与em
值一起使用。
只要字体相同(选择特定字体而不是像#34; monospace&#34;这样的通用字体会更好),这个技巧应适用于任何字体大小。
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
text-anchor = "middle"
dy = "0.25em">
a
</text>
</svg>
&#13;
答案 2 :(得分:1)
Firefox prior to version 40不支持显性基线中的值中间值(它将其视为中心),并且没有版本支持对齐基线。
我担心对齐基线和显性基线的实现目前是一个雷区,因为IE不支持SVG文本,Firefox只支持显性基线,并且它的实现与该属性不完全一致铬的。