0

I'm creating a cover of my website. I use js to make the image shows at center vertically. Here is code:

function middle(){  
        var windowHeight=window.innerHeight;  
        var infographic=document.querySelector("#infographic img");  
        var imgHeight=parseFloat(window.getComputedStyle(infographic).height); 

        infographic.style.maxHeight=(windowHeight-120)+"px";

        infographic.style.marginTop=(windowHeight-imgHeight)/2+"px";  

        console.log(windowHeight);
        console.log(imgHeight);
        console.log(infographic.style.marginTop);
        console.log(infographic);
    }  
    middle();

Everything works well on Chrome. But when I open the site on Safari, it not works well evertime. Sometime the image shows at the bottom and what console log of "imgHeight" is 0, while I have not change any of the code, just hit the refresh button.

1 Answers1

0

You could use flex to vertically and horizontally center an image, like this:

.img-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Much cleaner, faster, no need to rerun a script on window resize. Note: In the example above your image is the only child of img-container and img-container gets the whole width and height of the viewport. Example here.

Kostas Siabanis
  • 2,989
  • 2
  • 20
  • 22