How to make a video background fixed while the text is scrolling?

770 views Asked by At

When I did add the video for the background it's only there for the top part of the page but I what it to be there for the rest of the page is scrolling

<div class="hero">
<video autoplay loop muted plays-inline class="back-video">
   <source src="/pexels-rostislav-uzunov-5680034.mp4" type="video/mp4">
</video>
<div>
   <nav>
      <img src="/401-logo.png" class="logo">
      <ul>
         <li><a href="#">HOME</a></li>
         <li><a href="#">POPULAR</a></li>
         <li><a href="#">ABOUT</a></li>
      </ul>
   </nav>
</div>
<div class="content">
   <h1>Code Engine</h1>
   <a href="#">Get Started</a>
</div>

CSS

 .hero{
     width: 100%;
     height: 100vh;
     background-image: linear-gradient(rgba(12,3,51,0.3),rgba(12,3,51,0.3));
     position: relative;
     padding: 0 5%;
     display: flex;
     align-items: center;
     justify-content: center;
}
 .content{
     text-align:center;
}
 .content h1{
     font-size: 160px;
     color: #fff;
     transition: 0.5s;
}
 .content h1:hover{
     -webkit-text-stroke: 2px #fff;
     color: transparent;
     .content a{
         text-decoration: none;
         display: inline-block;
         color: #fff;
         font-size: 24px;
         border: 2px solid #fff;
         padding: 14px 70px;
         border-radius: 50px;
         margin-top: 20px;
    }
     .back-video{
         background-attachment: fixed;
         position: absolute;
         right: 0;
         bottom: 0;
         z-index: -1;
    }
     @media(min-aspect-ratio: 16/9){
         .back-video{
             width: 100%;
             height: auto;
        }
    }
     @media(max-aspect-ratio: 16/9){
         .back-video{
             width: auto;
             height: 100%;
        }
    }
1

There are 1 answers

0
Henrique V. Sartori On BEST ANSWER

Your .back-video is an video tag, so background-attachment will not work here (this property only works on elements with background such as an background-image);

To use the video as an background to the actual page you must use position:fixed and object-fit:cover (so the video doesn't stretch while fitting in the aspect-ratio).

The video should also be height: 100vh and width: 100vw (or 100%) to fit the whole screen. There is no need to add @media to check min and max aspect-ratio of the window since object-fit:cover will do the job to fit your video correctly in all window sizes.