So I want an img
to be displayed
Also, the image's original size is not known.
I've tried quite a few different options for this, including a flexbox one (to get the vertical center), but nothing seems to tick all the boxes.
Ideally I'd like this to be an all CSS solution of course, but I have been looking into some JS as well.
To center it, you can use the technique shown here: Absolute centering.
To make it as big as possible, give it max-width
and max-height
of 100%
.
To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit
as explained here.
.className {
max-width: 100%;
max-height: 100%;
bottom: 0;
left: 0;
margin: auto;
overflow: auto;
position: fixed;
right: 0;
top: 0;
-o-object-fit: contain;
object-fit: contain;
}
<img src="https://i.imgur.com/HmezgW6.png" class="className" />
<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >