JSFiddle - React, Tailwind, and code Playground
by oilvier
HTML
<div class="foo">
<img src="//placehold.it/400x300" alt="">
</div>
<div class="bar">
<img src="//placehold.it/400x300" alt="">
</div>
SCSS
@mixin aspect-ratio($width, $height) {
&:before {
content: "";
width: 1px;
margin-left: -1px;
float: left;
height: 0;
padding-top: $height / $width * 100%;
}
&:after { /* to clear float */
content: "";
display: table;
clear: both;
}
}
.foo {display:flex; align-items:center; justify-content:center; @include aspect-ratio(400px, 300px); background-color:tomato;}
.bar {position: relative; overflow: hidden; background-color:firebrick;
&:before {content:""; display: block; padding-bottom:percentage(300/400); width: 100%; height: 0;}
& > img {position: absolute; top:50%; left:50%; max-width:100%; max-height: 100%; transform:translate(-50%,-50%);}
}
.foo,
.bar {max-width:600px;}