CSS is catching up. It no longer has support , but object-fit: contain does exactly what you want (EDIT 11/17: Edge now has partial support, which makes IE11 the only browser without support). Just put this in your css rule for img and change max-width: 100% and max-height: 100% to width: 100% and height: 100% . Here is the codepen .
.Container { height: 100vh; width: 100vw; background: red; display: flex; justify-content: center; align-items: center; } img { height: 100%; width: 100%; object-fit: contain; } body { margin: 0; }
<div class="Container"> <img src="https://unsplash.it/2000/1500"> </div>
If IE does not support object-fit , this is a transaction breaker, then there is javascript polyfill for it. Here is a bit more about this from css-tricks .
You can also get the same effect with background-image , but it just looks like a cheat.
Just add this to .Container :
background-image: url(http://d13rap2ac6f4c9.cloudfront.net/image_assets/quarry_medium.jpg?1410945487); background-size: contain; background-repeat:no-repeat; background-position: center;
Then completely remove the img tag. The effect is the same, but without the actual element in .Container . It should be noted that with this method display: flex is not even required.
Here is another codepen for this method.
.Container { height: 100vh; width: 100vw; background: red; background-image: url(https://unsplash.it/2000/1500); background-size: contain; background-repeat: no-repeat; background-position: center; } body { margin: 0; }
<div class="Container"> </div>
the support here is much better and there are even more things you can play with. Once again, here is an almanac entry from css tricks
source share