垂直居中SVG标签

Cuv*_*uva 13 css html5 svg center

我正在试图找到一种方法来垂直居中我的SVG标签.

基本上,这是一个简化的SVG代码,我试图集中:

<svg height="272" style="background-color:transparent;margin-left: auto; margin-right: auto;" width="130" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g style="font-size: 0.7em;" transform="scale(1 1) rotate(0) translate(0 270)">
        <g id="1" style="font-size: 0.7em;">
            <image height="32" width="32" x="49" xlink:href="../../images/JOB.GIF" y="-270"/>
        </g>
    </g>
</svg> 
Run Code Online (Sandbox Code Playgroud)

我可以毫不费力地将它放在页面的中间(水平方向),但是我希望它也可以垂直居中.

我可以添加包装器,但我想知道这样做的通用方法,不依赖于SVG大小和窗口大小.

我尝试了多种方法,但没有任何效果.

谢谢,

Mac*_*cki 19

我更新了这个答案,因为当前的浏览器有更好的解决方案.

多么聪明的人说,第一年你学习HTML和CSS,再过几年你学习高级的javascript,五年后你终于学会了如何垂直居中div.

垂直/水平对齐css中的任何内容都可以使用它.

<div class="outside">
    <div class="inside">Whatever</div>
</div>
Run Code Online (Sandbox Code Playgroud)

和css:

.outside{
    position:relative;
}
.inside{
    position:absolute;
    top:50%;
    bottom:50%;
    transform:translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是元素不会产生高度.

老答案:

你有高度和宽度,所以你可以使用 margin : auto auto;

或者把它放在div中

position:absolute ;
left:50% ;
margin-left: -(half of width of image)px;
top:50% ;
margin-top: -(half of height of image)px;
Run Code Online (Sandbox Code Playgroud)

第二个会更好,如果你将用它做一些东西(javascript动画或其他东西)

我没有检查它,但也许你可以使用svg的第二个选项(没有外部div)


Cuv*_*uva -2

我最终使用了一些 JS 代码来做到这一点。

我正在使用这里的解决方案:Best way to center a <div> on a page Vertical and Horizo​​ntal?

这是:

div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
Run Code Online (Sandbox Code Playgroud)

}

但问题是,如果 SVG 大于窗口大小,它就会被裁剪。这是我使用过的JS代码onLoad

var heightDiff = window.innerHeight - svg.height.baseVal.value;
var widthDiff = window.innerWidth - svg.width.baseVal.value;
if (heightDiff > 0)                                                                                                                
    svg.style.marginTop = svg.style.marginBottom = heightDiff / 2;
if (widthDiff > 0)
    svg.style.marginLeft = svg.style.marginRight = widthDiff / 2; 
Run Code Online (Sandbox Code Playgroud)