Neat trick for CSS object-fit fallback on Edge (and other browsers)

“Post Tiles”
<div class=”post__image-container”>
<a href=”blogpost.html”>
<img src=”pic.jpg” class=”post__featured-image”>
</a>
</div>
.post__featured-image {
width: 120px;
height: 120px;
object-fit: cover;
}
if ( ! Modernizr.objectfit ) {
$('.post__image-container').each(function () {
var $container = $(this),
imgUrl = $container.find('img').prop('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')')
.addClass('compat-object-fit');
}
});
}
.post {
&__image-container {
width: 120px; // the same width and height as for the <img>
height: 120px;
&.compat-object-fit {
background-size: cover;
background-position: center center;
.post__featured-image { // hide image if object fit is not supported - opacity to 0 for the link area
opacity: 0;
}
}
}
&__featured-image {
width: 120px;
height: 120px;
object-fit: cover;
}
}

--

--

Web developer and dev/CEO at ProteusThemes. Sometimes windsurf-ish digital nomad. Ex. astrophotographer and student of astrophysics.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store