Search the blog

When embedding videos into a responsive website you can make the iframes have a percentage width to fit your content but the problem is the height never changes. This jQuery code will ensure your videos always maintain a specified aspect ratio.

$(window).on('resize', function() {

    $('iframe').each(function() {
        var $this = $(this);
        if ($'video-aspect-ratio')) {
            var dimensions     = $'video-aspect-ratio');
            dimensions         = dimensions.split(':');
            var newHeight     = ($this.width() / dimensions[0]) * dimensions[1];
            newHeight         = parseInt(newHeight);
            $this.css('height', newHeight + 'px');


You can then set aspect ratio on a per-video basis like this (note the data-video-aspect-ratio="16:9"):

<iframe src="" width="640" height="360" frameborder="0" data-video-aspect-ratio="16:9" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

You can then set the width to whatever you like and the video will always stay in the correct proportions.

Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.