2017-03-07 104 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>