jQuery(function($) { var viewport = $('.viewport'), frame = viewport.find('iframe'), frameRatio = 16 / 9; $(window).on('resize', function() { var width = viewport.outerWidth(), height = viewport.outerHeight(), ratio = width / height, targetWidth = width, targetHeight = height; if (ratio > frameRatio) { // viewport is wider than video // correct the height targetHeight = width / frameRatio; } else { // viewport is taller than video // correct the width targetWidth = height * frameRatio; } frame.css({ width: targetWidth, height: targetHeight }); }).trigger('resize'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="viewport"> <iframe src="//www.youtube.com/embed/1La4QzGeaaQ?autoplay=1"></iframe> </div>
.viewport { height: 50vh; width: 50vw; position: relative; border: 1px solid red; margin: 10% 25%; } iframe { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; }