TL;DR; I’ve made a polyfill for CSS3 Object-fit. Download it from Github here: https://github.com/steveworkman/jquery-object-fit
The need for object-fit
A month ago, I was looking into creating a responsive grid full of images for a client. The width of the columns would vary depending upon device, and the dimensions and aspect ratio of the provided images could not be guaranteed.
The issue for me is keeping the images looking great, without skewing the dimensions and distorting the results, but I also needed them to expand or shrink to fit the boxes that they had been provided with.
Knowing CSS, the property
background-size: cover|contain would do this perfectly (See this A List Apart article for lots more detail), but this is for background images, and semantically, the images in my grid are part of the content, so should not be background images.
Looking for an equivalent, I found Object-fit: part of the CSS3 Image Values and Replaced Content spec. Unfortunately, browser support for this is very poor; this is the current browser implementation of this property:
As you can see, as of September 2012, only Opera support this feature! Side note: there is one other browser (there has to be for this to be for the spec to reach candidate recommendation) which is the HP TouchPad, not very useful for the majority of users
The polyfill is based on jquery-object-fit by Simon Schmid, to which I’ve made some improvements:
- Added support for
- Fixed the implementation for IE and Firefox
- Added feature detection so it uses the native implementation where possible
- Made it re-calculate on resizing the browser for responsive layouts
- Added a more tests to the suite
What you get is a simple polyfill for object-fit which follows the spec as closely as it can. There is one main difference:
- In a native implementation the image size remains the same and the picture within the image changes its dimensions, revealing grey letterboxed content. In the poly fill, an extra div is created around the image to take its dimensions and then the image is resized within that to provide the effect.
My thanks to Chris Mills of Opera for his articles and helping to explain how on earth all this works, and to Tab Atkins and the CSS WG for spelling it out. Hopefully there will be some more work on this feature soon. You can track the status of its implementation in Gecko (Firefox) and Webkit (Chrome et al) on their bug trackers (see links).
Please, let me know what you think in the comments and on github.