Flexible Embedded Media
Unfortunately the
max-width
property doesn’t work well for all instances of media, specifically around iframes
and embedded media. When it comes to third party websites, such as YouTube, who use iframes for embedded media this is a huge disappointment. Fortunately, there is a work around.
To get embedded media to be fully responsive, the embedded element needs to be absolutely positioned within a parent element. The parent element needs to have a
width
of 100%
so that it may scale based on the width of the viewport. The parent element also needs to have a height
of 0
to trigger the hasLayout
mechanism within Internet Explorer.
Padding is then given to the bottom of the parent element, the value of which is set in the same aspect ratio of the video. This allows the height of the parent element to be proportionate to that of it’s width. Remember the responsive design formula from before? If a video has an aspect ratio of 16:9,
9
divided by 16
equals .5625
, thus requiring a bottom padding of 56.25%
. Padding on the bottom and not the top is specifically used to prevent Internet Explorer 5.5 from breaking, and treating the parent element as an absolutely positioned element.HTML
<figure>
<iframe src="https://www.youtube.com/embed/4Fqg43ozz7A"></iframe>
</figure>
CSS
figure {
height: 0;
padding-bottom: 56.25%; /* 16:9 */
position: relative;
width: 100%;
}
iframe {
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}