Reputation: 139
I am looking for simple solution to always keep aspect ratio of a video but also to always fit the video inside the browser window for both the width and the height.
So far all the solutions I have found have been fitting only by width, but I need also to fit height. :}
Upvotes: 0
Views: 11156
Reputation: 391
You could try the CSS only route. YouTube had the solution I was looking for which was keeping width, and height in a 16:9 ratio.
video {
width: 100%;
min-height: 480px;
height: calc((9 / 16) * 100vw);
max-height: calc(100vh - 169px);
}
With HTML5, the aspect of the video will mold to the parent no matter the video's ratio.
Upvotes: 1
Reputation: 3489
Bootstrap does this. The trick is that CSS padding bottom is computed based on the width of the element.
.video-container {
position: relative;
overflow: hidden;
height: 0;
padding-bottom: 56.25%; /* calculate by aspect ratio (h / w * 100%) */
}
.video-container .video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="video-container">
<video class="video"></video>
</div>
See this example. It works with <embed>
, <object>
, <iframe>
, and <video>
tags. My example is just a colored <div>
that keeps its' aspect ratio constant.
Upvotes: 3
Reputation: 698
Try with Javascript...
function updateHeight()
{
var videoHeight = 9 * videoDom.offsetWidth / 16;
videoDom.style.height = vidoeHeight + "px";
}
window.onload = function()
{
updateHeight();
}
window.onresize = function()
{
updateHeight();
}
Assuming your video has 16:9 aspect ratio.
Upvotes: 1
Reputation: 2823
I wrote this for images originally for another question on SO, but it should work for just about any element. Just change the first variable to match your video element. You can also drop the for loop if you are only resizing a single element.
JS:
function resize() {
var img = document.getElementsByTagName('img');
var w = window.innerWidth;
var h = window.innerHeight;
//console.log(w);
//console.log(h);
for (i = 0; i < img.length; i++) {
var ratio = (img[i].clientHeight / img[i].clientWidth);
if (img[i].clientHeight > h && img[i].clientWidth < w) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientHeight <= h && img[i].clientWidth < w && ratio > 1) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientWidth >= w) {
img[i].style.width = w + "px";
}
if (img[i].clientHeight < h && img[i].clientWidth <= w && ratio < 1) {
img[i].style.width = w + "px";
}
}
}
resize();
window.onresize = resize;
JSFiddle: https://jsfiddle.net/hopkins_matt/k7t26sw5/
Upvotes: 1