Fitvids (github link) is an open source javascript library built by Chris Coyier and Paravel which makes the width of videos in a web page fluid. To be precise, videos within a DOM element.
How fitvids works
It a pretty nifty piece of javascript. Here is how it works.
- Its wraps the video in a wrapper div with 100% width (no height setting)
- The wrapper div has a padding-top according to the aspect ratio ( height/width*100%). e.g. If height is half of width, it is 50%.
- The video element’s original height and width are removed and both are set to 100%.
- The video element is positioned in the wrapper div with css style position:absolute. This ensures that video element just fits in the padding of the parent wrapper div. Please note that had it been position:relative, the video element would have started after the padding.
For complete code here is github link.
Fitvids Demo
In this example we display a video where fitvids.js has not been applied. You can resize the page and see what happens to the video. The video should not resize. Once you click on “apply fitvids code”, the following code is executed.
jQuery('body').fitVids();
Now video should resize with resize of the page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="/js/jquery.fitvids.js"></script> <iframe width="560" height="315" src="http://www.youtube.com/embed/NxJ0W-yz0LQ" frameborder="0" allowfullscreen></iframe> <br/><input type=button id="button1" value="click here to apply fitvids code" /> <div id="msg"></div> <script type="text/javascript"> jQuery("#button1").click(function() { jQuery('body').fitVids(); jQuery('#msg').text('fitvids applied...'); }); </script>