Saturday 1 March 2014

Responsive Flexible Embed Container

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
  1. <figure>
  2. <iframe src="https://www.youtube.com/embed/4Fqg43ozz7A"></iframe>
  3. </figure>
CSS
  1. figure {
  2. height: 0;
  3. padding-bottom: 56.25%; /* 16:9 */
  4. position: relative;
  5. width: 100%;
  6. }
  7. iframe {
  8. height: 100%;
  9. left: 0;
  10. position: absolute;
  11. top: 0;
  12. width: 100%;
  13. }

Flexible Embedded Media Demo

100% WIDE CONTAINER
75% WIDE CONTAINER
50% WIDE CONTAINER