JSFiddle - React, Tailwind, and code Playground
by Tushar Jadhav
CSS
div {
width: 100px;
height: 100px;
}
JavaScript
$(document).ready(function () {
$('img:visible').each(function () {
// For visible images only
var imageWidth,
imageHeight,
aspectRatio;
var parentWidth = $(this).parent().width(),
parentHeight = $(this).parent().height();
if (this.naturalWidth > parentWidth || this.naturalHeight > parentHeight) {
aspectRatio = this.naturalWidth / this.naturalHeight; // Actual image width and height
if (this.naturalWidth > this.naturalHeight) {
imageWidth = parentWidth - 10;
imageHeight = imageWidth / aspectRatio;
} else {
imageHeight = parentHeight - 10; // Leave some space
imageWidth = imageHeight * aspectRatio;
}
$(this).css({
'width': imageWidth,
'height': imageHeight
});
}
});
});