css – Object-fit property: cover; for IE and Edge

Question:

Is there some way to force the property object-fit: cover; work with IE and Edge? I know there is a thing called Polyfill, I don't know what to do with it. Please help me solve the problem with object-fit: cover; for IE and Edge.

Answer:

I propose to do the following hack: put an image in the background to the block and apply the background-size: cover property to it, which works in IE and Edge. This version will be in pure CSS and will work much faster than polyfills in JS.

However, if you really need to use img , you can polyfill IE:

var Detect = {
init: function () {
    this.browser = this.searchString(this.dataBrowser);
},
searchString: function (data) {
    for (var i=0;i<data.length;i++) {
        var dataString = data[i].string;
        var dataProp = data[i].prop;
        this.versionSearchString = data[i].versionSearch || data[i].identity;
        if (dataString) {
            if (dataString.indexOf(data[i].subString) != -1)
                return data[i].identity;
        }
        else if (dataProp)
            return data[i].identity;
    }
},
dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "IE",
        versionSearch: "MSIE"
    }
]
};
Detect.init();

if(Detect.browser == 'IE'){
   var bgImg = document.querySelector("#bg img");
   imgUrl = bgImg.getAttribute('src');
   bg.innerHTML += '<div class="img" style="background-image: url(' + imgUrl + ')">';
}
#bg{
    height: 100vh;
    width: 100%;
    position: relative;
}
#bg img{
    object-fit: cover;
    height: 100%;
    width: 100%;
}
#bg .img{
    background: #fff no-repeat 50% / cover;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
<html>
<body>
    <div id="bg">
        <img src="https://1000.tech/img/bg0.jpg">
    </div>
</body>
</html>
Scroll to Top
AllEscort