Html – CSS background video sizing issue with large videos

cssfullscreenhtmlvideo

I'm having problems resizing to keep the aspect ratio with large videos. I'm using this demo code: https://codeconvey.com/fullscreen-html5-responsive-video-background/

My problem is that I can get centering the video to work correctly, and the video resizes keeping the aspect ratio if the window is larger than the video, but a 1920×1080 video is not resizing down to fit the height or width of the browser on smaller screens (say, a laptop at 1440px wide). It seems that the video never scales down from it's original size.

It's as if the body doesn't understand that the viewport is smaller than 1920×1080 because, I suspect, it's defining 100% width based on the video element width. If I drop in a 1280x720p video into this code the resizing works flawlessly as the video always resizes up to fill the browser screen.

I did try wrapping the video in a container element, but didn't see an improvement, changing the relative/fixed/absolute positions in any combination as well as defining width height for html, body, container div, anything.

I don't want to rely on javascript if possible. I also want to use a 1080p video for quality purposes. Scaling up a 720p video does not work for my needs on this specific project.

What I need: responsive background video that covers the entire browser window, using a 1080p video, at the smallest size the video can be to fit the screen while keeping the video's aspect ratio. (The video must scale down on smaller screens)

Best Answer

Is this what you are looking for?

<style>
    #video-bg {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        overflow: hidden;
    }

    #video-bg > video {
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
</style>

<div id="video-bg">
    <video autoplay loop>
        <source src="Boat_15.mp4" type="video/mp4">
        Your browser does not support the video tag. I suggest you upgrade your browser.
    </video>
</div>

Take from here:

https://fvsch.com/code/video-background/

This takes advantage of object-fit which is relatively new in the CSS world so be careful for compatibility.

I believe there will always be minor scaling issues when stretching a video across a background like this because the viewport will most likely not match the scaling dimensions of the video. However, I think this is the appropriate solution to your problem as is scales one dimension of the video as necessary to cover the background without scaling outside the viewport.