2017-03-07 107 views
0

這是我的代碼:位置SVG項目相對於文本

<?xml version="1.0"> 
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
    <svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1"> 
    <text id="t1" x="50%" y="50%" text-anchor="middle">Hello World</text> 
    <g transform="translate(0,0) rotate(0)"> 
    <rect x="0" y="0" width="10" height="10" fill="blue" /> 
    </g> 
    </svg> 

這給我的Hello World和矩形。我想知道如何定位我的矩形相對於我的文本。我認爲這會做到這一點,但根據我上面的代碼矩形應該坐在文本的頂部,但它不。

編輯:我試過,但它並沒有改變什麼:

<?xml version="1.0"> 
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
    <svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1"> 
    <g transform="translate(0,0) rotate(0)"> 
    <rect x="0" y="0" width="10" height="10" fill="blue" /> 
    </g> 
<text id="t1" x="50%" y="50%" text-anchor="middle">Hello World</text> 

    </svg> 
+0

畫家的典範。最後在上面。 –

+0

@RobertLongson對不起,我不明白。我試圖將文字放在以下,但這沒有什麼區別。 – Jimmy

+0

@RobertLongson更新 – Jimmy

回答

2

這是接近你想要什麼?

<svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1"> 
 
    <rect x="0" y="0" width="100%" height="100%" fill="blue" /> 
 
    <text id="t1" x="50%" y="50%" text-anchor="middle" dy="0.3em">Hello World</text> 
 
</svg>

的正確值用於dy,得到垂直居中的文字,是特定的字體。您可能需要調整該值以匹配您選擇的任何字體。在我看來,這是一個更可靠的替代方案,如alignment-baseline

0

另一種方法,你可以嘗試!也許它會適合你......

p { 
 
    font-size: 42px; 
 
} 
 

 
p>svg { 
 
    width: 60px; 
 
    height: 60px; 
 
    display: inline-block; 
 
    position: relative; 
 
    top: 28px; 
 
}
<div style="display:none"> 
 
    <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
 
    <symbol viewBox="0 0 20 20" id="box"> 
 
     <g transform="translate(0,0) rotate(0)"> 
 
     <rect x="0" y="0" width="12" height="12" fill="blue" /> 
 
     </g> 
 
    </symbol> 
 
    </svg> 
 
</div> 
 
<p> 
 
    <svg> 
 
    <use xlink:href="#box"></use> 
 
    </svg> Hello World 
 
</p>