注意以下片段:
<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>
Chrome 将该片段呈现为:
而在 FireFox 上,这是结果:
如何以跨浏览器兼容的方式复制此代码段?
最佳答案
Firefox 不支持“alignment-baseline”。 尝试使用属性“dominant-baseline”,它应该适用于两者(Chrome 和 Firefox 但不适用于 IE,见下文)。
看看这个old answer
根据 SVG 规范,对齐基线仅适用于“tspan”、“textPath”、“tref”和“altGlyph”。我的理解是它用于抵消它们上方的“文本”对象。我认为您正在寻找的是显性基线。
它适用于 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>
关于html - 如何使用具有跨浏览器兼容性的 SVG 垂直对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372877/