Responsive fullscreen youtube video with no black bars?

后端 未结 8 1780
执笔经年
执笔经年 2020-12-08 10:20

I have a fullscreen youtube video embedded on my website.

\"enter

It looks goo

8条回答
  •  离开以前
    2020-12-08 11:04

    This is pretty old but people may still need help here. I needed this too so have created a Pen of my solution which should help - http://codepen.io/MikeMooreDev/pen/QEEPMv

    The example shows two versions of the same video, one as standard and the second cropped and centrally aligned to fit the size of the full parent element without showing the hideous black bars.

    You need to use some javascript to calculate a new width for the video but it's really easy if you know the aspect ratio.

    HTML

    CSS - The height and width o the videoWrapper can be anything, they can be percentages if you so wish

    .videoWrapper {
      height:600px;
      width:600px;
      position:relative;
      overflow:hidden;
    }
    
    .videoWrapper iframe {
        height:100%;
        width:100%;
        position:absolute;
        top:0;
        bottom:0;
    }
    

    jQuery

    $(document).ready(function(){
        // - 1.78 is the aspect ratio of the video
        // - This will work if your video is 1920 x 1080
        // - To find this value divide the video's native width by the height eg 1920/1080 = 1.78
        var aspectRatio = 1.78;
    
        var video = $('#videoWithJs iframe');
        var videoHeight = video.outerHeight();
        var newWidth = videoHeight*aspectRatio;
        var halfNewWidth = newWidth/2;
    
        video.css({"width":newWidth+"px","left":"50%","margin-left":"-"+halfNewWidth+"px"});
    
    });
    

    This can also be triggered on resize to ensure it remains responsive. The easiest (probably not most efficient) way to do this is with the following.

    $(window).on('resize', function() {
    
        // Same code as on load        
        var aspectRatio = 1.78;
        var video = $('#videoWithJs iframe');
        var videoHeight = video.outerHeight();
        var newWidth = videoHeight*aspectRatio;
        var halfNewWidth = newWidth/2;
    
        video.css({"width":newWidth+"px","left":"50%","margin-left":"-"+halfNewWidth+"px"});
    
    });
    

提交回复
热议问题