How does Zurb's Foundation deal with responsive video?

Sep 9, 2013

A Mystery to Solve

Zurb's Foundation CSS Framework is pretty amazing. I'm constantly delighted by the simple, elegant and effective solutions they've come up with for the myriad challenges in building responsive sites. One of my favourites has always been their responsive video implementation. Until today, I just used it without even thinking about how it works.

However, this morning I had to apply the same functionality on a site that didn't have the framework installed. It took me a bit longer than I'd expected to dissect it - about 15 minutes. That's after Googling and not finding the answer...so here it is. Save that 15 minutes for something else, like hanging with your kids or making something awesome with MODX :P

Background

Check out Zurb's blog post on the responsive video problem. Note: "The major issue with scaling is to ensure you keep the ratio of width to height constant and adjust the height appropriately."

Clues

The solution is comprised of two parts:

  1. The .flex-video wrapper
  2. The embed code, intended to be an iframe element with a youtube or vimeo URL as the src

Here I've isolated the applicable styles to make it easy ;) See if you can spot the nifty device they used:

.flex-video {
    position: relative;
    padding-top: 0;
    padding-bottom: 57.25%;
    height: 0;
    margin-bottom: 16px;
    overflow: hidden;
}
.flex-video iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}  

At first I was thrown off by the fact that the iframe element is absolutely positioned, and the relatively-positioned container had a height of 0. How does the browser compute its height then, and in the exact required aspect ratio to boot?

Mystery Solved

Of course the answer is beautiful in its simplicity: padding-bottom: 57.25% !!

CSS padding, when expressed as a percentage, is relative to the width of the containing element. So 57.25% of the width is the exact height required to display vimeo iframes of any width, based on the aspect ratio of the vimeo player. The value is different for YouTube videos, thus the different classes available in Foundation for different aspect ratios.

The amazing thing about this is that support for an element with a specific aspect ratio, but non -specific height and width, has been there all along - right under our noses - with percent-based padding! Nice one, Zurb. For this and many other reasons you get a gold star :D