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:
iframe { width: 100%; height: 56.25vw; /* 100 * (9/16) */ }
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:
iframe width: 100% height: (100 * (3/4))vw
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.
.vid margin: 2rem border: 30px solid red iframe width: 100% height: calc((100vw - 60px) * (9/16)) display: block
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.
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post