'Automatic height when embedding a YouTube video?
i've embed a YouTube video on my website but the trouble is that i need the height to automatically adjust based on the width and the aspect ratio of the video. So if my width is 1280, my height should be 720 if the video is 16:9. I've tried using 'VW' and 'VH' units but these don't seem to work with an iframe. My width is already set proportionally.
My code is below:
<iframe style="margin-right: 1%; margin-left: 1%;" width="98%" height="" src="https://www.youtube.com/embed/HwzQbfde-kE" frameborder="0"></iframe>
Solution 1:[1]
I was able to make a responsive iframe size using vw on both width and height of the style element because I know the amount of horizontal width I want the elements to use and then I calculate the height based on the width and the knowledge that the video is 16:9. If you want the video to consume 45% of the horizontal space above screen sizes of 893px and 90% otherwise, then:
.embedded-video-16-9 {
width: 90vw;
height: 50.625vw; /* 90*9/16 */
margin-left: 5vw;
margin-right: 5vw;
}
@media (min-width: 893px) {
.embedded-video-16-9 {
width: 45vw;
height: 25.3125vw; /* 45*9/16 */
margin-left: 2vw;
margin-right: 2vw
}
}
Used like:
<iframe
class="embedded-video-16-9"
src="https://www.youtube.com/embed/_TyJeKKQh-s?controls=0"
frameborder="0"
allowfullscreen=""
></iframe>
Solution 2:[2]
If you go for the entire viewport you can use following code:
iframe{
width: 100vw;
height: calc(100vw/1.77);
}
Solution 3:[3]
The html width attribute only accepts numbers ("valid non-negative integers"), not strings suffixed with units of measurement (%, px, vw, etc) as in the original question.
If you know the width of the iframe's container (in an absolute unit like px or vw, not %) then you can use css calc() for a one-line height solution in css:
.youtube-embed {
--container-width: 720px;
--ratio: calc(16 / 9); /* 1.77 */
width: 100%;
height: calc(var(--container-width) / var(--ratio));
}
Here's a responsive solution that accounts for horizontal padding on the container:
:root {
--video-ratio: calc(16 / 9);
--video-container-max-width: 640px;
--video-container-x-padding-sum: 2rem; /* eg, padding: 0 1rem */
}
.youtube-embed {
--video-container-width: calc(100vw - var(--video-container-x-padding-sum));
width: 100%;
height: calc(var(--video-container-width) / var(--video-ratio));
}
@media only screen and (min-width: 672px) {
.youtube-embed {
--video-container-width: var(--video-container-max-width);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Alex |
| Solution 3 |
