在span标签中居中对齐SVG

nci*_*iao 1 html css

我正在尝试将灰色框中的条形图居中对齐。我已经尝试了各种方法(例如文本对齐:居中,或设置显示:块,边距:0 自动)仔细阅读相关帖子,但它们似乎都不起作用。

这是小提琴:http : //jsfiddle.net/nickciao/F6R9C/93/

html:

<div id="Tile">
<h2>
     <span id="Top">0.0%</span>
</h2>
<ul class="Middle">
    <span>2.9k</span>
         USERS
    <span>BECAME ACTIVE</span>
</ul>
<div id="Bottom" >
    <div>
    <svg id="svg">
        <g transform="translate(5,5)">
            <rect y="23.33333333333333" x="15" height="11.666666666666671" width="5">
            </rect>
            <rect y="35" x="21" height="0" width="5">
            </rect>
            <rect y="25.666666666666686" x="27" height="9.333333333333314" width="5">
            </rect>
            <rect y="35" x="33" height="4.666666666666686" width="5">
            </rect>
            <rect y="25.666666666666686" x="39" height="9.333333333333314" width="5">
            </rect>
            <rect y="25.666666666666643" x="45" height="9.333333333333357" width="5">
            </rect>
            <rect y="25.666666666666686" x="51" height="9.333333333333314" width="5">
            </rect>
            <rect y="30.333333333333343" x="57" height="4.666666666666657" width="5">
            </rect>
            <rect y="32.666666666666686" x="63" height="2.3333333333333144" width="5">
            </rect>
            <rect y="32.66666666666664" x="69" height="2.333333333333357" width="5">
            </rect>
            <rect y="16.33333333333333" x="75" height="18.66666666666667" width="5">
            </rect>
            <rect y="32.666666666666686" x="81" height="2.3333333333333144" width="5">
            </rect>
            <rect y="35" x="87" height="0" width="5">
            </rect>
            <rect y="35" x="93" height="20.999999999999993" width="5">
            </rect>
            <rect y="35" x="99" height="34.999999999999986" width="5">
            </rect>
        </g>
    </svg>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

kir*_*der 6

在这里更新小提琴

默认情况下,SVG 元素是内联的,因此首先确保您已将其设置为显示块元素。您可以指定一个边距以将元素居中并适合其父容器内的元素:

#svgContainer svg {
    display: block;
    margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以利用“viewbox”属性来确保您的 SVG 元素将缩放以适应其父容器的边界:

<svg viewbox="0 0 120 80" height="80">
Run Code Online (Sandbox Code Playgroud)

在您的情况下,视图框的宽度/高度应始终与您显示的图形的大小相关。(假设您想显示整个图形,无论如何。)

这是关于视口和视框如何在 SVG 元素中一起播放的一个很好的参考:http : //jonibologna.com/svg-viewbox-and-viewport/