object-fit-images
🗻 Polyfill object-fit/object-position on
<img>
: IE9, IE10, IE11, Edge, Safari, ...
- Fast and lightweight (demo)
- No additional elements are created
- Setup is done via CSS
- Scaling is taken care by the browser (it uses
background-size
) srcset
supportsrc
andsrcset
properties and attributes keep working:img.src = 'other-image.jpg'
Alternative solutions
Comparison | bfred-it /object-fit-images🌟 |
constancecchen /object-fit-polyfill |
tonipinel /object-fit-polyfill |
---|---|---|---|
Browsers | IEdge 9-14, Android<5, Safari<10 | <- Same | "All browsers" |
Tags | img |
image video picture |
img |
cover/contain |
💚 | 💚 | 💚 |
fill |
💚 | 💚 | 💚 |
none |
💚 | 💚 | 💚 |
scale-down |
💚 using {watchMQ:true} |
💚 | 💔 |
object-position |
💚 | 💚 | 💔 |
srcset support |
💚 Native or picturefill notes | 💚 | 💔 |
Extra elements | 💚 No | 💔 Yes | 💔 Yes |
Settings | 💚 via CSS | 💔 via HTML | 💔 via HTML |
Usage
You will need 3 things
-
one or more
<img>
elements withsrc
orsrcset
-
CSS defining
object-fit
and a specialfont-family
property to allow IE to read the correct valueor, if you also need
object-position
To generate the
font-family
automatically, you can use the PostCSS plugin or the SCSS/SASS/Less mixins.If you set the
font-family
via JavaScript (which must be followed by callingobjectFitImages()
), make sure to include the quotes in the property. -
the activation call before
</body>
, or on DOM ready;// if you use jQuery, the code is: $(function () { objectFitImages() });This will fix all the images on the page and also all the images added later (auto mode).
Alternatively, only fix the images you want, once:
// pass a selector;// an array/NodeListvar someImages = document;;// a single elementvar oneImage = document;;// or with jQueryvar $someImages = ;;You can call
objectFitImages()
on the same elements more than once without issues, for example to manually request an update of theobject-fit
value.
resize
Apply on You don't need to re-apply it on resize
, unless:
-
You're using
scale-down
, or -
your media queries change the value of
object-fit
, like this{ }
In one of those cases, use the watchMQ
option:
;// or objectFitImages(null, {watchMQ: true}); // for the auto mode
Install
Pick your favorite:
<!-- CDN is also available, but I suggest you concatenate JS files instead --><!-- Visit https://cdnjs.com/libraries/object-fit-images -->
npm install --save object-fit-images
var objectFitImages = ;
;
API
objectFitImages(images, options)
Both parameters are optional.
parameter | description | ||
---|---|---|---|
images |
Type: string , element , array , NodeList , null Default: null The images to fix. More info in the Usage section |
||
options |
Type: object Default: {} Example: {watchMQ:true}
|
License
MIT © Federico Brigante