html - 如何使用具有跨浏览器兼容性的 SVG 垂直对齐文本?

标签 html css svg cross-browser

注意以下片段:

<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 将该片段呈现为:

chrome

而在 FireFox 上,这是结果:

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/

相关文章:

html - 如何在html中为特定行实现滚动条

css - 降低 Twitter Widget 的最小高度

css - 使用 CSS 在悬停时转换 SVG 路径的填充属性

jquery - Chrome : Seems to add an invisible border when hovering over a tr

javascript - 使用 CSS3/Javascript 悬停时导航栏过渡高度

html - 文本旁边的下划线使它们分开

javascript - 使用 Javascript(不使用 modernizr)检测 CSS 转换?

html - 如何将 svg 填充效果应用于 div 类?

html - 如何拉伸(stretch)背景 SVG,使其始终通过 CSS 填充 div?

javascript - 无法从样式化的文本区域获取文本