Search code examples
htmlcssbootstrap-4bootstrap-5

How do I fit a video to the background of a web page using HTML/CSS and Bootstrap?


I'm trying to get the video to fit the screen. Currently it is massive and I can't figure out how to make the scroll bars disappear. Object-fit doesn't look like it's working as it is supposed to. Also, when I make the screen smaller obviously I want the video to scale with it.

HTML

<div class="video-background">
    <video autoplay muted loop>
        <source src="img/cocktail_pour.mp4" type="video/mp4">
    </video>
</div>

CSS

body {
    margin:0;
    padding:0;
}
.video-background {
    width:100%;
    height:100vh;
    overflow:hidden;
    display:flex;
    justify-content:center;
    align-items:center;
}

.video-background video{
    position:absolute;
    top:0;
    left:0;
    object-fit:cover;
}

Solution

  • This works across most browsers:

    HTML:

    <div class="video-background">
      <video autoplay muted loop class="video">
        <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4">
        Your browser does not support HTML5 video.
      </video>
    </div>
    
    <div class="content">
      <!-- CONTENT GOES HERE -->
    </div>
    

    CSS:

    .video { /* This is to make the video appear behind everything else */
      position: fixed;
      z-index: -1000; /* Z-Index is -1000 just to be safe */
      right: 0;
      bottom: 0;
      min-width: 100%; 
      min-height: 100%;
    }
    
    .content { /* This is for the content */
      position: fixed;
      z-index: 1; /* This can be set to any number greater than -1000. */
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      color: #f1f1f1;
      width: 100%;
      padding: 20px;
    }