r15bin
r15bin

Reputation: 15

HTML + CSS: How do I put text above a video on a scrollable website?

I built a website with several sections. Each section is fullscreen. To reach the next section, you need to scroll down.

The first section has a video background. I would like to put some text above the video, but can't find any solution, which lets me put text above the video only in section one.

HTML:

<main>
        <section id="one">
            <video src="xxx" autoplay loop muted></video>
            <div class="oneText">
                <p>Above video</p>
            </div>
        </section>
        <section id="two">
           <p>Random content<p>
        </section>
        <section id="three">
            <p>Random content<p>
        </section>
        <section id="four">
            <p>Random content<p>
        </section>
</main>

CSS:

main {
    height: 100vh;
    scroll-snap-type: y mandatory;
    scroll-behavior: smooth;
    overflow-y: scroll;
}

section {
    scroll-snap-align: start;
    height: 100vh;
}

section video {
    width: 100vw;
    height: 100vh;
    object-fit: cover;
    z-index: -5;
}

.oneText {
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -30%);
}

Position absolute (obviously) doesn't work...

Any help is appreciated! :)

Upvotes: 0

Views: 839

Answers (2)

James
James

Reputation: 631

position: absolute; is positioned relative to the nearest positioned ancestor

main {
  height: 100vh;
  scroll-snap-type: y mandatory;
  scroll-behavior: smooth;
  overflow-y: scroll;
}

section {
  scroll-snap-align: start;
  height: 100vh;
}

section video {
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  z-index: 1;
}

section#one {
  position: relative;
}

.oneText {
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -30%);
  z-index: 2;
}
<main>
  <section id="one">
    <video src="https://www.w3schools.com/html/mov_bbb.mp4" autoplay loop muted></video>
    <div class="oneText">
      <p>Above video</p>
    </div>
  </section>
  <section id="two">
    <p>Random content<p>
  </section>
  <section id="three">
    <p>Random content<p>
  </section>
  <section id="four">
    <p>Random content<p>
  </section>
</main>

Upvotes: 1

John
John

Reputation: 5335

You need to make the section of the first video relative. So add this to your CSS:

#one {
  position: relative;
}

Upvotes: 1

Related Questions