Home > Blockchain >  How do I get my background video which is on z-index: -1; to scroll with the page?
How do I get my background video which is on z-index: -1; to scroll with the page?

Time:12-31

I am fairly new to coding, therefore only using and familiar with HTML and CSS.

My goal For this page I'm working on, I want a video as a background and the video should scroll with the content of the page.

My situation As I understand it, you cannot use the background property for a video. Therefore I have used some code that puts the video at z-index: -1;, so that it acts as background and other content can go on top. This is working well. I have a bunch of content on top and it all works great.

My problem The only thing I can't get to work, is the video to scroll with the content of my page. Instead, it is fixed and stays in place while the content that is on top scrolls.

I have tried the following unsuccessfully:

  • background-attachment: scroll, applied to a container that includes the video
  • background-attachment: scroll, applied to the video itself
  • endless googling to find the answer

My question How can I have the video as my background and make it scroll with the page?

Thanks a lot for any insights you have.

(what I think is) The relevant HTML:

  <video id="background-video" autoplay loop muted poster="https://assets.codepen.io/7471668/truck-video.png">

(what I think is) The relevant CSS:

#background-video {
width: 100vw;
height: 625px;
object-fit: cover;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}

@media (max-width: 480px) {
#background-video { display: none; }
body {
  background: url("https://assets.codepen.io/6093409/river.jpg") no-repeat;
  background-size: cover;
}
}

CodePudding user response:

The line position: fixed makes the video stick in the same position when you scroll, so if you change that to position: absolute the video will remain as a background with other elements on top, but it will not be fixed as you scroll.

Mozilla position docs: https://developer.mozilla.org/en-US/docs/Web/CSS/position

  • Related