Object-fit cross-browser solution

dippas

dippas

Posted on November 1, 2020

Object-fit cross-browser solution

The object-fit CSS property is been very useful in websites nowadays, but there is still a caveat which is the need to support to Internet Explorer and/or EDGE (for some clients/projects at least).

So, with that in mind, there is a JavaScript snippet to make it cross-browser and which is simpler, lighter than the current polyfills out there.

First you'll need to add data-attributes in HTML & their respective CSS property:

HTML

<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
Enter fullscreen mode Exit fullscreen mode

CSS

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
Enter fullscreen mode Exit fullscreen mode

Then with less than 10 lines of JavaScript code, you'll have a cross-browser solution.

ES6 version

if ('objectFit' in document.documentElement.style === false) {
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('img[data-object-fit]').forEach(image => {
            (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
            image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
        })
    })
}
Enter fullscreen mode Exit fullscreen mode

Or if you don't use a transpiler, here's the transpiled version for ES5

if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]'), function (image) {
      (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
      image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

What does this code do?

It detects if the object-fit is not supported in the browser, if so, then replace the img for a svg

For the supported browsers it will run the CSS properties through the data-attributes

💖 💪 🙅 🚩
dippas
dippas

Posted on November 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related