Create a tall section with fixed background image

by davidxmartins

HTML

<section class="normal">
    <h2>Scroll Down to See the Effect</h2>
    <p>This section is very tall to demonstrate background immobility.</p>
    </section>


<div style="height: 100vh;">Scroll past this block</div>
<section class="section-parallax-sticky">
    <div class="parallax-content">
        <h2>Content that Sticks</h2>
        <p>This text will remain visible in the viewport while the background image scrolls underneath it.</p>
    </div>
</section>
<div style="height: 100vh;">Continue Scrolling</div>


    <section class="normal">
    <h2>Scroll Down to See the Effect</h2>
    <p>This section is very tall to demonstrate background immobility.</p>
    </section>

CSS

.normal {
  background: black;
  color: white;
  height: 100vh;
}


.section-parallax-sticky {
  /* 1. Define the section's height to control how long the effect lasts */
  height: 200vh; /* Make it tall enough to allow scrolling */
  
  /* 2. Parallax Background Setup (Image is pinned to the viewport) */
  background-image: url('https://cdn.pixabay.com/photo/2022/08/23/17/47/forest-7406241_1280.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center; 
  background-attachment: fixed; /* Essential for the Parallax effect */
}

.parallax-content {
  /* 3. Sticky Positioning */
  position: sticky;
  
  /* Pin the content to the top of the viewport */
  top: 0; 
  
  /* Optional: Center the text block visually */
  width: 80%;
  margin: 0 auto;
  padding-top: 50vh; /* Push content down to start lower in the section */
  
  /* Text aesthetics */
  color: white;
  text-align: center;
}