Chris P Chris P -5 years ago 84
HTML Question

Vertically Align an Image so that There is the Same Amount of Space Above it as there is Below it?

I am trying to make a simple webpage that displays a GIF as big as possible but right in the center of the page. I would like there to be the same sized gap above the image as there is below it. I am new to HTML and CSS etc. and I'm not sure how to word or demonstrate this (I'm, a complete noob) but here is a link to JSFiddle.

<!DOCTYPE html>
<title>Gandalf Sax Guy!</title>

body {
overflow: hidden;
background-color: black;
margin: 0;

img {
width: 100%;
height: 100%;


<img src=""/>

<audio autoplay sr>
<source src="">

Id like the image to be as big as possible but not distorted and work dynamically (Is that the right word?) so that it works with whatever window dimensions are given.

As you can see, I'd like the image to have an equal amount of "black space" above and below it. I know this sort of question gets asked a lot but I have been trying for almost 2 hours now and absolutely nothing is working for me.

Thank you in advance,

Chris :)


Thanks to Sebastian Motraghi, who solved my question but now the image does not fill the screen (I wouldn't want completely, because that would distort it). If anyone could help with that, that would be amazing!


Answer Source

flexbox to the rescue!


<div id="positioning-context">
    <img src=""/>


#positioning-context {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download