Neat trick for CSS object-fit fallback on Edge (and other browsers)
Yesterday I needed to implement the object-fit fallback in the most recent theme we’ve built at ProteusThemes. There is an element on a homepage we call “Post Tiles” and it shows most recent WP blogposts along with the associated featured images.
We didn’t want to generate multiple image sizes of all these images, so we decided to go with the object-fit.
Object-fit CSS property has a decent support in modern browsers, except in all IEs and even Edge (update 2017–10–18: Edge 16 now support object-fit). My first thought was to use a polyfill developed by Anselm Hannemann, but it turned out it is not working as expected in Edge (and it is not actively maintained anymore).
So after an hour or so I ended with a better and more lightweight solution. It is altogether 10 lines of JS and 10 lines of CSS code. Let’s assume your HTML looks like this:
<div class=”post__image-container”>
<a href=”blogpost.html”>
<img src=”pic.jpg” class=”post__featured-image”>
</a>
</div>
So you use the object-fit like this:
.post__featured-image {
width: 120px;
height: 120px;
object-fit: cover;
}
This will work beautifully, except in Edge and IE. But a very similar background-position: cover is working for IE 9+. So let’s use Modernizr for feature detection and fix this with some JS:
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');
}
});
}
This will copy the src of our image to the background image source of the container. Further we change our SCSS a little bit:
.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;
}
}
And that’s it. The class .compat-object-fit will only be added by JS if the browser doesn’t support object-fit.
Let me know on Twitter if you have any question.
Update 2016–10–06: object-fit in Edge is now marked with a high priority and in the backlog for implementation #.
Update 2017–03–14: object-fit in Edge is now under active development 🎉 #.
Update 2017–10–18: object-fit has been shipped in Edge 16!!! #
You might follow me on Twitter, but we both know Twitter is very noisy. So you can leave me your email and I will occasionally send you stuff I find useful.