CSS object-fit fallback for IE & MSEdge v2

<!-- After long way to re-configure the compatibility issue on MS Edge, Here it is. --> <!doctype HTML> <html> <head> <style> .cover-background { background-size: cover; background-repeat: no-repeat; background-position: center; } .img-invisible { visibility: hidden !important; } </style> </head> <body> <!-- You can use any type of '.class' name here --> <!-- Be sure to update this class as well: $('.image-hero-background') --> <figure class="image-hero-background"> <img src="https://placem.at/places?w=1600&h=900&txt=0&random=1" alt="Your Alt Name"> </figure> <!-- Modernizr script is a must --> <script src="https://cdn.jsdelivr.net/jquery/3.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/modernizr/2.8.3/modernizr.min.js"></script> <script> // The Magic Begins for IE & MSEdge 12+ function objectFit() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); var trident = ua.indexOf('Trident/'); var edge = ua.indexOf('Edge/'); if (msie > 0 || edge > 0 || trident > 0) { if ( ! Modernizr.objectfit ) { $('.image-hero-background').each(function(){ var $cover = $(this), imgUrl = $cover.find('img').prop('src'); if( imgUrl ) { $cover.css('backgroundImage', 'url(' + imgUrl + ')').addClass('cover-background').find('img').addClass('invisible'); } }); } } return false; } // Execute the function $(document).ready(objectFit); </script> </body> </html>
This is my new rendition from my previous Neat Trick for CSS Object-Fit fallback, though that current snippet supports only late Internet Explore 11 and below. I've decided to create another fallback which include MSEdge.

Requirements:
1. jQuery (latest version)
2. Modernizer (2.8.3 version)
3. Optimized CSS code
4. jQuery fallback function script of ObjectFit

Compatibility Cases:
http://caniuse.com/#search=object-fit

Fallback Explanation:
This version is much more easy to navigate or understand compare to my old version. You must have a parent-container before the `img` tag itself.

This is where the script create new attributes and duplicate the url of your image to mask it as a background using the parent-container. We use `visibility:hidden` to visually hide the image but leave track of image height to maintain the reflection of image ratio to its parent-container and render it as full-image.

@Bruno: I believe base on "caniuse.com", IE/MSEdge is the only desktop browser that are not fully supported the Object-Fit and Object-Position CSS attributes, including old Android/Mobile browsers. So, you can still use this attributes to all modern browsers.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.