HTML5 videos have intrinsic aspect ratios and tend to keep it, no matter what your CSS tells them to do.
I have a responsive video container that isn't 16:9, and I'd like the videos inside it to stretch to 100% width and 100% height, even if it breaks their original aspect ratio.
I've read about the CSS object-fit: fill property, which would solve my problem, but there's still a long way to go before modern browsers support it. So I guess I must turn to JavaScript to achieve what I need.
I came across this fiddle:
function scaleToFill(videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height();
if (videoRatio < tagRatio) {
$video.css('-webkit-transform','scaleX(' + tagRatio / videoRatio + ')')
} else if (tagRatio < videoRatio) {
$video.css('-webkit-transform','scaleY(' + videoRatio / tagRatio + ')')
}
}
$(function () {
$("#testVideo").click(function(evt) {
scaleToFill(document.getElementsByTagName("video")[0]);
});
});
However, I can't seem to get this code to work. The console tells me the videoWidth property cannot be read.
Quote from the HTML5 spec for
<video>
tags:As for videoWidth specifically, it seems to be supported by all major browsers, so I'm not sure what your problem is there.
To the best of my knowledge, the CSS transforms as shown in the jsfiddle you linked are not standardised in terms of their effect when it comes to
<video>
, but they all worked for me in IE10, and latest Chrome and Firefox. I wonder, however, if you tried to use the jsfiddle on a browser that wasn't Chrome. The script you supplied only adds webkit transforms, so I have modified it to make transforms on other renderers and increased the ratio so as to make the effect more apparent.Have a look at this new one. Hopefully it's what you wanted. In addition, here is a pure CSS one, as javascript really isn't required to make those changes unless you need to calculate the new ratio for some reason and can't have it static. The only issue is that the controls go out of sight, so I added an autoplay attribute.