2015-07-12 75 views
3

记住以下片段:如何垂直对齐使用SVG跨浏览器兼容的文本?

<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

我怎么能复制这个片断在一个跨浏览器兼容的方式?

+1

关联:[Firefox支持alignment-baseline元素?](http://stackoverflow.com/questions/19212498/firefox-support-for-alignment-baseline-property) – TylerH

回答

6

的“对准基线”不是Firefox支持。 尝试使用属性“显性基线”,它应该都适用于(Chrome浏览器& Firefox,但不适用于IE浏览器,请参阅下文)。

看这个old answer

根据SVG规范,对齐基线仅适用于 “TSPAN”, “textPath”, “TREF” 和 “altGlyph”。我的理解是,它用于抵消上面的“文本”对象。我认为你在寻找的是主导 - 基线。

它适用于Chrome和Firefox而不是IE浏览器。如果你也想在IE的垂直居中的文本,你必须使用一个工作arournd这样的:

<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> 

+0

你的第一句话有点误导,这是错误的(正如你在第三段中解释的那样)。 – TylerH

+0

对不起,我会尽力解释更好 –

3

最简单的跨浏览器的解决方案只是使用dy属性与em值。

只要字体是相同的(这将是更好的选择一个特定的字体,而不是一个通用的一个像“等宽”),这一招应该适用于任何字体的大小。

<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>

1

火狐prior to version 40不支持显性基准值中正确(它把它作为中心),并没有版本支持对齐基线。

恐怕对齐 - 基线和显性 - 基线的实现目前有点雷区,因为IE不支持SVG文本,Firefox只支持显性基线,并且它的实现不太一致与Chrome的。