By utilizing CSS alone, it is feasible, although cross-browser support may be lacking. Hello, Internet Explorer:
img {
object-fit: cover;
max-width: 100%;
max-height: 100%;
min-width: 100%;
min-height: 100%;
}
Witness it in action:
.sized-container {
width: 25vw;
height: 25vw;
display: inline-block;
float: left;
}
.sized-container img {
object-fit: cover;
max-width: 100%;
max-height: 100%;
min-width: 100%;
min-height: 100%;
}
body {margin :0;}
<div class="sized-container">
<img src="https://loremflickr.com/640/360">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/360/640">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/100/100">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/1000/1000">
</div>
To achieve a solution compatible across all browsers, JavaScript has to come into play.
Hide the <img>
elements while extracting their src
values to set as container backgrounds. These containers have background-size:cover
to deliver precise sizing and cropping behavior as needed.
This solution also enlarges small images to adapt to the width/height of their parent containers:
let containers = document.querySelectorAll('.sized-container');
for (let i = 0; i < containers.length; i++) {
var container = containers[i],
image = container.querySelector('img');
if (image)
container.style.backgroundImage = 'url(' + image.getAttribute('src') + ')'
}
.sized-container {
width: 25vw;
height: 25vw;
background: transparent 50% 50% no-repeat /cover;
float: left;
}
.sized-container img {
display: block;
width: 100%;
height: 100%;
opacity: 0;
}
body { margin: 0;}
<div class="sized-container">
<img src="https://loremflickr.com/640/360">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/360/640">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/100/100">
</div>
<div class="sized-container">
<img src="https://loremflickr.com/1000/1000">
</div>
If jQuery is used, the script can be more concise:
$('.sized-container').each((i,e) => {
let img = $('img', e);
if (img.is('img'))
$(e).css({backgroundImage:'url(' + img.first().attr('src') + ')'});
})
Note: Ideally, when generating the markup, setting the background-image
of the parent should be considered to avoid fetching it from images using JavaScript. Nevertheless, for accessibility purposes (such as screen readers, title attributes, etc.), keeping the <img>
elements hidden is recommended.