A Javascript polyfill for browsers that don't support the object-fit CSS property.
npm install must-fitobject-fit CSS property. Unsure of what the object-fit does? Essentially object-fit is to ![]()
tags what background-size is to background-image. You can check out the MDN page for more details.- Lightweight - 2.6KB (1.8KB with the basic version)
- Vanilla Javascript - works with or without jQuery
- Supports IE 9+, iOS 7-, and Android 4.4-
- Supports object-position
- Works with image, video, srcset, and picture
- Plug and play - just include the .js file and set data attributes on your elements.
- Please note: This plugin makes the assumption that the parent container is acting as a picture frame, and already has a height & width set.
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).
If you're wondering: why bother using tags versus background-image? Here's a couple reasons:
1. tags have better SEO/crawling visibility.
2. In cases where images are dynamically returned and can't simply be added to your stylesheets (e.g., CMS's), you're forced to inline your background-image. This solves that somewhat-ugly-looking inline CSS.
3. background-image doesn't work with video or picture elements.
Of course, there's still plenty of cases where using a background image makes more sense than a regular image.
Initialization:
``html
`
Customized object-fit/object-position:
`html
If you're only interested in using the basic polyfill (which assumes
object-fit: cover and object-position: 50% 50%), you can save yourself some bytes by using:`html

``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.