JSFiddle - React, Tailwind, and code Playground
by thiemeljiri
HTML
<div class="container">
<img src="http://placehold.it/1920x800" alt="Some image withy any aspect ratio you want">
</div>
<div class="container">
<img src="http://placehold.it/800x1920" alt="Tall...">
</div>
<div class="container">
<img src="http://placehold.it/800x800" alt="...or square">
</div>
<div class="container">
<img src="http://placehold.it/300x200" alt="Smaller images aren`t resized to bigger than original size.">
</div>
CSS
.container {
height: 0;
padding-bottom: 100%; /* Or 75% for 4:3 aspect ratio */
position: relative;
overflow: hidden;
/* For this example only */
background: #987;
margin-bottom: 50px;
}
.container img {
display: inline-block;
max-width: 90%; /* You can use different numbers for max-width and max-height! */
max-height: 75%;
width: auto;
height: auto;
position: absolute;
left: 50%; /* This sets left top corner of the image to the center of the block... */
top: 50%; /* This can be set also to bottom: 0; for aligning image to bottom line. Only translateX is used then. */
-webkit-transform: translate(-50%,-50%); /* ...and this moves the image 50 % of its width and height back. */
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
/* Fallback for IE8 */
@media all\0 {
.container img {
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
}