Chris P Chris P - 5 months ago 23
HTML Question

How to vertically center an image and make it fill available width

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 the image to be centered vertically. Here is a link to JSFiddle.

<!DOCTYPE html>
<html>
<head>
<title>Gandalf Sax Guy!</title>
</head>
<body>
<style>

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

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

</style>

<img src="http://eul.ddns.net/gandalf/gif.gif"/>

<audio autoplay sr>
<source src="http://eul.ddns.net/gandalf/sax.mp3">
</audio>


I'd like the image to be as big as possible, but not distorted, and work dynamically.

As you can see, I'd like the image to have an equal amount of "black space" above and below it.

Answer

flexbox to the rescue!

html:

<div id="positioning-context">
    <img src="https://placekitten.com/140/50"/>
</div>

css:

#positioning-context {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}