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



我在这里检查了现有的答案。不幸的是,它根本没有帮助。我的问题特定于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>

我正在尝试水平和垂直地将 svg 中心居中。我尝试过使用弹性框和绝对定位。由于某些原因,它不居中。

PS:svg图像是虚拟图像,但大小是准确的。

你可以

用css和JavaScript来做到这一点。

的 HTML。

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <svg id="Layer_1"></svg>
    </body>
</html>

CSS的

body {
    margin: 0px;
}
svg {
    position: relative;
}

JavaScript。

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"
}

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

最新更新