Advertisement
  1. Web Design
  2. CSS
Webdesign

Instant Fluid Videos with Viewport Width Units

by
Difficulty:IntermediateLength:ShortLanguages:

Intrinsic ratios are an approach to expanding and contracting elements on a web page, allowing them to be fluid whilst at the same time constraining their proportions. Thierry Koblentz first proposed the idea back in 2009.

They’re frequently used in conjunction with video since neither the width or the height of an iframe (the element typically used when embedding video content) doesn’t automatically scale for fluid websites.

Long story short: video isn’t responsive by default.

Huge write-ups have been done on the subject. The most famous of which is Thierry Koblentz’s A List Apart article which suggests doing a lot of stuff with position: relative and some hacks for old Internet Explorer, and by the time you’re done implementing it, you’ve added dozens of lines of code to your markup and CSS just to make a video responsive. Argh!

Viewport Width Unit

Thankfully we now have access to the vw sizing unit and as long as you don’t have to support old Android devices or IE8, it’s relatively safe to use.

All we have to do is set our iframe’s width to 100% and then set its height to the following formula: (100 * ratio)vw.

In the case of most YouTube videos, your ratio will be 16:9 (otherwise expressed as 9/16), so to make a YouTube video responsive use the following CSS code:

This is made even easier when you use a preprocessor like Sass, LESS, or Stylus, as you can pass whatever ratios you’d like on the fly. For instance, for a 4:3 video, you could write:

Adding Margins and Borders

What happens if we want to add a margin or border to it? It seems to throw everything out of whack. To fix that, we simply need to add our border and margins to a wrapping element and then subtract the border from our height using calc. We add display: block to our iframe to keep it from creating a gap on the bottom of the video.

The next “gotcha” is what if we want our video to rest inside of a container that only spans 70% of the viewport? Simple, we just change the 100vw in our calc function to 70vw.

Conclusion

That’s all there is to it! Super easy responsive videos. For more details on ratios and vw units check out Jason Talbert’s brilliant CodePen.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.