Search code examples
htmlcssvideoscreenbackground-size

Video doesn't scale correctly in width


I have a slight issue. I have a video which I would like to adjust to the browser, it shouldn't stretch, but neither should there be any with space visible

HTML:

<video src="Wereldbol.mp4" onclick="this.play();" id='wereldbol' preload="auto" ></video>

CSS:

#wereldbol {
    position: absolute;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    z-index: -1;
    overflow: hidden;
    background-size:cover;
}

background-size: cover; is causing the issue that the video would be off-center, is there any alternative way to cover the browser's full width and height? At the moment width: 100% and height: 100% don't quite fix the issue because it would leave the image to have a white bar on the left and right, eventhough the video scales correctly. Is there any way to fix this issue?


Solution

  • If I understand you correctly, what you are trying to achieve is keep the video’s aspect ratio, but make it adapt to its surroundings without stretching the video out of proportion. Here’s how I do it:

    Wrap the video element in a div, like this:

    <div class="video-wrapper">
        <video src="Wereldbol.mp4" onclick="this.play();" id='wereldbol' preload="auto" ></video>
    </div>
    

    Then use the following CSS:

    .video-wrapper {
      position: relative;
      width: 100%;
      max-width: 100%;
      height: 0;
      padding: 56.25% 0 0 0; /* 100%/16*9 = 56.25% = Aspect ratio 16:9 */
      overflow: hidden;
      border: 0;
    }
    
    .video-wrapper video {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
    }
    

    EDIT: Here’s a plunker: Adjust the viewport-width to see how it works.