I found this JSFiddle which does pretty much exactly what I'm trying to accomplish - https://jsfiddle.net/q1rjg9zd/
Notice that you can resize the output frame, and the video will always fill the entire frame, without any space above/below the video to maintain the 16:9 aspect ratio.
I'm trying to get this exact same effect, except I'd like it to be done in a wrapper div, instead of filling the whole viewport. E.g. I can have a div that is 1000px in height and 500px in width and the video would behave the same as in this example.
I'm really struggling to work out how to do this, since the JSFiddle example uses vw and vh measurements, and when I try to convert those to percentages and fixed pixel measurements, the effect is lost.
* {
padding: 0;
margin: 0;
}
.video-background {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
}
iframe {
position: absolute;
top: 50%;
left: 50%;
width: 100vw;
height: 100vh;
transform: translate(-50%, -50%);
@media (min-aspect-ratio: 16/9) {
height: 56.25vw
}
@media (max-aspect-ratio: 16/9) {
width: 177.78vh
}
}
<div class="video-background">
<iframe src="https://www.youtube.com/embed/biWk-QLWY7U?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&mute=1" frameborder="0" controls=0 allowfullscreen></iframe>
</div>
I found one solution that works for me:
Working examples:
short explanation:
@container query instead of @mediacontainer-type to sizecqw & cqh)All major browsers support this by now, but as always: check you requirements: https://caniuse.com/?search=%40container
Hope this helps you out :)
/*
Arbitrarily sized & positioned element that will
contain the embedded video as background.
*/
.arbitrarily-placed-and-sized-parent-element {
position: relative;
top: 50px;
left: 50px;
width: 50vw;
height: 20vh;
}
/*
This element contains the iframe, will take it's size from
it's parent and will behave like an image/video
with object-fit: cover.
*/
.video-embed-object-fit-cover {
position: absolute;
/* ensure positioning regardless of parent flex settings */
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 100%;
/* important */
container-type: size;
/* cut off overflowing video */
overflow: hidden;
}
.video-embed-object-fit-cover > iframe {
position: absolute;
/* keep video centered both vertically and horizontally */
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
/* force aspect ratio based on parent container */
@container (min-aspect-ratio: 16/9) {
height: 56.25cqw;
}
@container (max-aspect-ratio: 16/9) {
width: 177.78cqh;
}
/* prevent interaction */
pointer-events: none;
}
<div class="arbitrarily-placed-and-sized-parent-element">
<div class="video-embed-object-fit-cover">
<iframe src="https://www.youtube.com/embed/biWk-QLWY7U?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&mute=1" frameborder="0" controls="0"></iframe>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With