CSS. Object-fit: cover simulation for IE

ie-object-fit

The CSS object-fit property of use to specify how a <img> tag can be resized to fill its container.

This property is not available in Internet Explorer (IE), causing images to be distorted in this browser, and especially in the case of using grids.

A possible solution to make it compatible with other browsers can be the following: transfer the image to the background, where if there is the equivalent resizing property in IE (background-size).

To do it in a general way to the web page that we are developing, we can use a script to perform this function if the browser is IE.

In this example we will carry out this process for the <img> of the .photo-img and .wp-post-image classes, which we will have defined in the HTML code or will be given by the CMS. We will modify the functions.php file, adding the img-background.js file in the js folder of our theme (WordPress). In the functions.php file, we add the following code to load the function that will perform the indicated process:

global $is_IE;
if( $is_IE ) {
 add_action('wp_enqueue_scripts','insertar_js');
 function insertar_js(){
   wp_register_script('dw-script-img',get_stylesheet_directory_uri().'/js/img-background.js',array('jquery'),'1',true);
   wp_enqueue_script('dw-script-img');
 }
}

which will only act if the browser is IE. The img-background.js file will contain the following code:

jQuery(function($){
  $(document).ready(function(){
    $("img.img-photo,img.wp-post-image").each(function(){
      $(this).attr({ "style":
        "background-image:url("+$(this).attr('src')+");"
        +"background-size: cover;"
        +"background-position: 50% 50%;"
        +"height: 100%;"
      });
      $(this).removeAttr( "src" );
    });
  });
});

where, through the style attribute we put the source image in the background-image property, we resize it with the background-size:cover property; we position it in the center (background-position: 50% 50%) and adjust it to its container (height: 100%). Finally, the attribute of the source image (src) is removed.

Keep in mind that the <img> parent container must have its height defined. In a generic way we can define this last aspect for certain containers in the style file (style.css) and that only acts in IE

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
  .container img {
     max-height: 300px;
  }
}
Llamar a Doowebs Teléfono de Doowebs 653836347