Alternative option of object-fit:cover for internet explorer

Ok I solved it with this

HTML

<div class="grid-image" style="background-image: url(images/15.jpg);"></div>

CSS

  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;  

You can really create an alternative for ie9+ using Modernizr. So you can still using object fit where it's supported. In this example I use jQuery too.

if ( ! Modernizr.objectfit ) {
  $('.grid-image').each(function () {
      var $wrapper = $(this),
      imgUrl = $wrapper.find('img').prop('src');
      if (imgUrl) {
         $wrapper
         .css('backgroundImage', 'url(' + imgUrl + ')')
         .addClass('compat-object-fit')
         .children('img').hide();
      }  
   });
 }

Obviously if any user wants to browse the web with software from the 20th century he will get a 20th century version of the web. It's like trying to watch the 70mm scenes from Interstellar (or any modern 16:9 film) in a 4:3 tube tv, you won't see all the features of the docking scene.


My approach will ideally work in all browsers as it a simple CSS trick. Please check the images below to see the effect it has.

The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic should work in all browsers.


Tags:

Html

Css