Show whole image and centre it
<!-- HTML -->
<div class="big-img-container">
<img src="..." alt="Large image">
</div>
/* CSS */
<style>
.big-img-container {
display: flex;
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
.big-img-container img {
object-fit: contain;
max-height: 100%;
max-width: 100%;
display: block;
margin: auto;
}
</style>
How does this work? The big-img-container
limits the frame of the image to the size of the browser window. The property-value pair object-fit: contain
makes the magic happen. This scales the image down while maintaining the original aspect ratio. This means that there’s no stretching of the image. The max-height
and max-width
properties ensure that the img
doesn’t break out of the area defined by the big-img-container
. Finally, the good old display: flex
and margin: auto
combination put the img
in the center of the screen. Altogether, these few lines of CSS form the basis of a nice centred image effect.