2017-05-05 67 views
0

我有一個問題讓我的SVG文本居中在Firefox和Chrome中。我還沒有仔細檢查其他瀏覽器。我目前在Firefox中橫向居中,但在Chrome中,它偏離了幾個像素。我注意到在Chrome瀏覽器中,文字並沒有完全填滿<svg>元素的寬度,導致右側的空間偏離居中。在Firefox中,垂直居中也與底部的幾個像素不同。這怎麼解決?不知道我在代碼中做錯了什麼。要查看問題的實時視圖,請在兩個瀏覽器中查看https://wsplays-members.com/results/並查看「我們的認證結果」標題。提前致謝。在Chrome和Firefox中居中SVG文本漸變

.widget-title { 
 
    border-bottom: solid 3px black; 
 
    font-family: 'anton', sans-serif; 
 
    font-size: 32px; 
 
    font-weight: 700; 
 
    margin: 2px auto 0; 
 
    background: url(images/lines.png) bottom repeat-x; 
 
    line-height: 1; 
 
    padding-bottom: 16px; 
 
    text-align: center; 
 
    text-transform: uppercase; 
 
}
<!--SVG TITLE HEADER--> 
 
<div class="widget-title"> 
 
    <svg height="30px" width="270px" viewBox="0 0 100% 100%" preserveAspectRatio="xMidYMid"> 
 
     <defs> 
 
     <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%"> 
 
      <stop offset="0%" style="stop-color:rgb(226, 69, 38);stop-opacity:1" /> 
 
      <stop offset="100%" style="stop-color:rgb(34, 34, 34);stop-opacity:1" /> 
 
     </linearGradient> 
 
     </defs> 
 
     <text fill="url(#grad1)" x="0" y="97%">Our Certified Results</text> 
 
     Sorry, your browser does not support inline SVG. 
 
    </svg> 
 
</div> 
 
<!--END SVG TITLE HEADER-->
所有的

回答

1

首先,你viewBox是無效的。您不能在viewBox中使用百分比值。因此它將被忽略。但你的情況你不需要它。

無論如何,你的問題是你正在將SVG放在<div>的中心,但你並沒有將文本放在SVG中。

如果您希望文本以SVG爲中心,請將其放置在正確的中心並使用text-anchor="middle"

在你的情況,你會希望將文本元素更改爲:

<text fill="url(#grad1)" x="135" y="97%" text-anchor="middle">Our Certified Results</text> 

在下面的例子中我增加了SVG的width,文本x位置,因爲我們要使用更寬字體。

.widget-title { 
 
    border-bottom: solid 3px black; 
 
    font-family: 'anton', sans-serif; 
 
    font-size: 32px; 
 
    font-weight: 700; 
 
    margin: 2px auto 0; 
 
    background: url(images/lines.png) bottom repeat-x; 
 
    line-height: 1; 
 
    padding-bottom: 16px; 
 
    text-align: center; 
 
    text-transform: uppercase; 
 
} 
 

 
svg { 
 
    border: solid 1px green; 
 
}
<!--SVG TITLE HEADER--> 
 
<div class="widget-title"> 
 
    <svg height="30px" width="450px"> 
 
     <defs> 
 
     <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%"> 
 
      <stop offset="0%" style="stop-color:rgb(226, 69, 38);stop-opacity:1" /> 
 
      <stop offset="100%" style="stop-color:rgb(34, 34, 34);stop-opacity:1" /> 
 
     </linearGradient> 
 
     </defs> 
 
     <text fill="url(#grad1)" x="225" y="97%" text-anchor="middle">Our Certified Results</text> 
 
     Sorry, your browser does not support inline SVG. 
 
    </svg> 
 
</div> 
 
<!--END SVG TITLE HEADER-->

+0

不敢相信,我失去了一些東西那麼簡單。非常感謝您花時間幫助解釋。學習了不少。 :) – kma1289