Search code examples
htmlcanvasmp4

Using and MP4 as a div background and fill the space as the window is resized


I have tried using the tag but when the window is resize I need the video to fill the space as the window is resized. At the largest scale it fills the space and as is shrinks it starts to add a lot of white space at the top and bottom.

HTML

<video playsinline autoplay muted loop poster="images/user_item.mp4" class="w-100" style="">
    <source src="images/user_item.mp4" type="video/mp4">
</video>

CSS

video { 
    position: absolute;
    min-width: 100%;
    min-height: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    height: 300px;
    border-radius: 5px 0 0 5px;
}

Is it possible to play the video in a canvas and resize the canvas and have it fill the entire space provided?


Solution

  • No need for a canvas, just use CSS. In particular here you want the object-fit property.

    By default for video it's set to contains, meaning it will set the size of the media to the smallest side and add borders to the largest, keeping the aspect-ratio of the media.

    From your description it's quite unclear if you want the cover which keeps aspect-ratio but cuts the media,

    video { 
        position: absolute;
        width: 100vw;
        height: 100vh;
        top: 0;
        left: 0;
        object-fit: cover;
    }
    <video src="https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm" autoplay loop muted></video>

    or fill, which just stretches/shrinkes the media.

    video { 
        position: absolute;
        width: 100vw;
        height: 100vh;
        top: 0;
        left: 0;
        object-fit: fill;
    }
    <video src="https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm" autoplay loop muted></video>

    And for future readers, note that this CSS property can also be set to <canvas>.