JSFiddle - React, Tailwind, and code Playground
by web5me
HTML
<p>The following image centers itself on both axes inside a container with a fixed width/height ratio (4:3) and scales down if the container gets smaller than the image.</p>
<p>Since the image itself has a ratio of 1:1 it gets cropped on its top and bottom edge in this example if you scale down the container.</p>
<p>You can manipulate image and cropping behaviour by altering min-width, min-height, max-width and max-height values on the image tag.</p>
<div class="img-ratio">
<div class="img-centering">
<img src="http://placehold.it/400x400" alt="" />
</div>
</div>
CSS
img {
display: block;
}
.img-ratio {
position: relative;
/* width/height ratio 4:3 */
padding-bottom: 75%;
}
.img-centering {
/* fill out the whole ratio wrapper */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* for cropping behaviour */
overflow: hidden;
}
.img-centering img {
/* center image on both axes */
position: absolute;
top: -9999px;
right: -9999px;
bottom: -9999px;
left: -9999px;
margin: auto;
/* cropping behaviour */
max-width: 100%;
}