Image object fit fallback polyfill for Internet Explorer and Edge

Here is a way to make object fit for images behave similarly in Internet Explorer and Edge.

The basic idea is that we have an img  that we want to scale into different sizes but also proportions (e.g get wider or higher than the original image).

We allow some clipping occur to enable this. This is especially useful in responsive website where you need to support different viewports and perhaps number of columns for a list of images etc.

More info here and examples of clipping of image etc:
https://www.w3schools.com/css/css3_object-fit.asp

We use this css styling to enable that on the img element:

Unfortunately object-fit is supported by all major browsers except Internet Explorer and Edge. A way to make it work in those browsers is to copy the image src to the image container element and use the background* css propeties instead.

The code and idea is taken from here:
https://medium.com/@primozcigler/neat-trick-for-css-object-fit-fallback-on-edge-and-other-browsers-afbc53bbb2c3

I have tweaked the above example a bit and here is my version of it. See comments section in the link above for plain js versions etc.

Usage

We mark the img with the class “img-cover”:

Source files

Download here: img-cover-source.zip

The js has dependencies on jquery 3.2.1 and modernizr 3.6 (I have tested with those versions).

The html should look like this when the polyfill is working in Internet Explorer or Edge:

The container (a-element) gets the compat-object-fit class and inline style background image is copied from its contained img src. Also the css file will set the contained img to opacity 0 in favor of container bg image instead.