A polyfill for browsers that don't support the
object-fitCSS property. Unsure of what the
background-image. You can check out the MDN page for more details.
You can check out the bare-bones demo here. Note that the plugin simply won't do anything if you're on a browser that already supports object-fit, so you'll want to test it on IE or older iOS/Android browsers.
Unlike object-fit-images or Primož Cigler's method (both excellent alternatives if you'd rather not use this one), this polyfill does not set a background image on the parent container, but instead resizes and repositions the image (using inline CSS for height, width, absolute positioning, and negative margins).
The polyfilled item will receive the class
object-fit-polyfillif styling issues occur that require overrides.
If you're wondering: why bother using
background-image? Here's a couple reasons:
tags have better SEO/crawling visibility.
background-imagedoesn't work with
Of course, there's still plenty of cases where using a background image makes more sense than a regular image.
If you're only interested in using the basic polyfill (which assumes
object-position: 50% 50%), you can save yourself some bytes by using:
If you need to dynamically call the polyfill on the fly for any reason (for example, carousels or lazy-loaded images), you can do so quite easily:
// Rerun the polyfill on all elements with the data attribute objectFitPolyfill();
// Rerun the polyfill on a single DOM node var element = document.querySelector('.foo'); objectFitPolyfill(element);
// Rerun the polyfill on multiple elements var elements = document.querySelectorAll('.bar'); objectFitPolyfill(elements);
// Rerun the polyfill with a jQuery selector objectFitPolyfill($('.baz'));
npm install objectFitPolyfill yarn add objectFitPolyfill # Or: bower install objectFitPolyfill
import 'objectFitPolyfill'; // Or: require('objectFitPolyfill');
Note that in SPA's, you must manually call
window.objectFitPolyfill()after component mount / once you're sure your media is loaded in & available. See this example React usage.
If you'd like to make feature requests such as IE 8- or adding object-position support for Safari, feel free to open an issue or pull request! It's doable and on my radar, but I probably won't get to it without some prodding.