Odo Object Fit

A polyfill for CSS' object-fit: cover; If the browser supports object-fit, it will not run. The media element should have full width and height as well as the object-fit property.

This component handles image and video loading internally and sets the size of the media element when its metadata is available.

Support

IE9+

Native support: Chrome 31, Firefox 36, Safari 7.1, Opera 19, iOS Safari 8, Android browser 4.4.4.

Your browser does not support CSS object-fit. This component will adjust images and video.

Dependencies

None.

Cover vs. Nothing

a placeholder image
a placeholder image
With object fitting.
Without object fitting.

Markup

<img id="my-cover" class="my-cover" src="https://placehold.it/350x150" alt="">

Styles

These rules are required. You must add them to your image or video which is being fitted.

.my-cover {
  width: 100%;
  max-width: none;
  height: 100%;
  object-fit: cover;
}

Script

ObjectFit does not keep track of fitted elements. When its parent element changes size, you must fit the object again.

OdoObjectFit.cover(document.getElementById('my-cover'));
window.addEventListener('resize', function() {
  OdoObjectFit.cover(document.getElementById('my-cover'));
});

Responsive Image and Video

Responsive image with img[srcset]
Autoplaying cinemagraph Continuous Wreckage

Deferred image loading

These images do not have a src attribute. It's added after the page has loaded.

a placeholder image
a placeholder image
With object fitting.
Without object fitting.

Pass an array of elements

It can be array-like, like a Nodelist or arguments.

OdoObjectFit.cover(document.querySelectorAll('.coveralls'));

Using Contain

You may also specify that the media element should be completely contained/visible within its parent element.

Landscape img[srcset]
Landscape video

Setup

Use the static contain method to polyfill object-fit: contain.

.my-contain {
  width: 100%;
  max-width: none;
  height: 100%;
  object-fit: contain;
}
OdoObjectFit.contain(document.querySelectorAll('.my-contain'));