How to Maintain the Aspect Ratio of Embedded Videos
In this tutorial, we'll explore a few helpful CSS tricks for maintaining the aspect ratio of embedded videos on screen. These solutions are perfect for responsive displays and work for locally embedded videos and third-party embedded videos like YouTube iframes. In this example, we'll be working with iframes, just note that these examples will work with other HTML elements, as well.
Aspect Ratio with Custom CSS
Let's create our embedded YouTube iframe first:
<iframe class="video" src="YouTube embed URL"></iframe>
Now, let's add the CSS:
.video {
width: 100%;
aspect-ratio: 16 / 9;
}
Here, we're setting the iframe's width containing the .video
class to "100%", ensuring the video always stretches the entire width of its parent element.
Next, we're applying the aspect-ratio
CSS rule with a value of "16 / 9" to ensure the video always retains its correct width and height when resized and for different screen sizes. It also ensures that no negative space exists within the edges of the video.
aspect-ratio
is supported in the major browsers.
Aspect Ratio with Tailwind CSS
Tailwind CSS comes equipped with pre-defined classes that do the heavy lifting for you! Here's an example that will accomplish the same result as above without creating any additional custom CSS rules:
<iframe class="aspect-video w-full" src="YouTube embed URL"></iframe>
Relative & Absolute Positioning
You can also go the old route of creating a parent element with relative positioning and an iframe or video element with absolute positioning by offsetting the bottom padding of the parent container to maintain the aspect ratio.
Here's the HTML code:
<div class="video-container">
<iframe src="YouTube embed URL"></iframe>
</div>
And here's the CSS code:
.video-container {
position: relative;
padding-bottom: 56.25%;
}
.video-container iframe {
width: 100%;
height: 100%;
position: absolute;
}
The padding-bottom
value is determined by the video's aspect ratio. Here is a complete list of the different percentage values you can use for the different aspect ratios:
1:1
- 100%16:9
- 56.25%4:3
- 75%3:2
- 66.66%8:5
- 62.5%
Conclusion
I prefer running with the aspect-ratio
option, but each solution has its benefits, particularly when considering browser support.
Created: July 11, 2023
Comments
There are no comments yet. Start the conversation!