如何垂直和水平定位SVG图像中心?

时间:2018-03-22 18:57:11

标签: html css css3 svg flexbox

我在这里查看现有答案。不幸的是,它根本没有帮助。我的问题特别针对 SVG图像



* {
    box-sizing: border-box;
}

html, body{
  
  max-width: 1280px;

  width: 100%;
}

body{
  margin: 0 auto;
  display: flex; 
  flex-direction: column; 
  align-items: center;
  justify-content: center;

}

<div class="wrapper">

        <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 807.2 400.42">
            <defs>
                <style>.cls-1 {
                    fill: #d1cfbf;
                }</style>
            </defs>
        </svg>
        </div>
&#13;
&#13;
&#13;

我试图将svg中心水平和垂直居中。我尝试过使用Flexbox和绝对定位。由于某些原因,它不对齐中心。

PS:svg图像是虚拟图像,但尺寸确切。

1 个答案:

答案 0 :(得分:0)

你可以用css和JavaScript来做。

HTML。

body {
    margin: 0px;
}

svg {
    position: relative;
}

CSS

function _id(e){
    return document.getElementById(e)
}

window.onload = function(){
    _id("Layer_1").style.marginTop = (window.innerHeight/2) - (_id("Layer_1").getBoundingClientRect().height/2) + "px";

    _id("Layer_1").style.marginLeft = (window.innerWidth/2) - (_id("Layer_1").getBoundingClientRect().width/2) + "px"
}

JavaScript。

{{1}}

无论宽度或高度如何,这都应该将svg元素保持在中心位置!

相关问题