2015-07-12 73 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的。