Published on Sun, 01/13/2019 - 19:06
Polyfill object-fit cover for img and video HTML elements.
Note, this will only work as intended when the img/video element is a single child and the parent has an explicit width/height.
Assumptions:
img/video has width: 100%, height: auto
- Important because you want to maintain the images aspect ratio and of course width: auto, height: 100% doesn't work. Container has an explicit height (e.g either through padding-bottom or vh)
Mozilla's developer site does a good job:
"The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit."
Assumptions:
img/video has width: 100%, height: auto
- Important because you want to maintain the images aspect ratio and of course width: auto, height: 100% doesn't work. Container has an explicit height (e.g either through padding-bottom or vh)
What is object-fit: cover
Mozilla's developer site does a good job:
"The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit."
// Edge supports object-fit on img but not video elements if('objectFit' in document.documentElement.style === false || /Edge/.test(navigator.userAgent)) { (function () { var $container = $('container-selector'); var $video = $('element-selector'); $container.css({position: 'relative'}); $video.css({width: '100%', height: 'auto', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)'}); var videoAspectRatio = $video.width() / $video.height(); var resizeFunction = function() { var containerAspectRatio = $container.width() / $container.height(); if (containerAspectRatio < videoAspectRatio) { // Increase width in order to scale the image, up until they are same height ( works due to height: auto) // NOTE: object-fit contain then would have to scale down var scale = $container.height() / ($container.width() / videoAspectRatio); $video.css('width', 100 * scale + '%'); } }; resizeFunction(); $(window).on('resize', resizeFunction); })(); }
Add new comment