Responsive Image full screen and centered - maintain aspect ratio, not exceed window
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;" >
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.