I have a very simple question. How do I make sure an iframe's aspect ratio is responsive?
The iframe is a YouTube Video, and I want the aspect ratio of the iframe to remain 16:9 no matter the browser window size.
Here is my current code for mobile devices:
@media screen and (max-width: 600px) {
iframe, body {
max-width: 90vw;
height: auto;
}
}
iframe {
border: 0;
width: 600px;
height: 338px;
}
Because YouTube iframes do not keep aspect ratio automatically, I need a way to keep the aspect ratio of the video, and the width to be 90vw. The problem with this current code is that, it only adapts the width, leaving unwanted letterboxing.
You really don't need media query to achieve this but if you want, you can shift it inside media query. So, how is it being achieved?
Since, we know we need the
aspect ratio of 16:9
and the width should not exceed 90vw, thus the height should also not exceed 50.85vw. And we set themax-height and max-width
according to your absolute dimension limits that is 600px and 338 px of the container. Now, setting theiframe dimensions to the 100% of the container
, it inherits that dimensions. :)Wrap the iframe in a container.