0

I have check existing answers here. Unfortunately, it did not help at all. My question is particular to SVG image.

* {
    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>

I am trying to center the svg center horizontally and vertically. I have tried using Flexbox and absolute positioning. For some reasons, it does not align center.

PS: svg image is a dummy image but size is exact.

forethought
  • 2,913
  • 2
  • 16
  • 26
  • possible duplicate of https://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically – john_h Mar 22 '18 at 19:00
  • 1
    Without the actual SVG we can't help. It's possible the viewbox is wrong. Your demo doesn't actually demonstrate the issue. – Paulie_D Mar 22 '18 at 19:11
  • You are missing `justify-items:center` in body i think.. That should work if you are using flexbox – MJN Mar 22 '18 at 20:31

1 Answers1

0

You can do it with css and JavaScript.

The HTML.

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

The CSS

body {
    margin: 0px;
}

svg {
    position: relative;
}

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

This should keep the svg element in the center no matter what the width or height is!