Search code examples
imagescrollcss-position

How do you make content in a website cover the hero image as scrolling down


I know this has been a duplicate question but I have tried to make two div with one being the hero image and the other being the content. I wanted the hero image to stay in position when the user scrolls and get covered by the other div but when I try to make the hero image div position fixed the whole image just disappears. I know fixed position gets the element overlapped but when I try to play with z index the image still doesn't show up. Am I doing something wrong?

HTML:

    <div class='heroImgContainer'>
    </div>
    <div class='content'>
    </div>

CSS:

.heroImgContainer {
    background-image: url('.png');
    height: 400px;
    position: fixed;
    z-index: 1;
}


.content {
    height: 1000px;
    background-color: black;
    position: relative;
}

Solution

  • You need to adjust the z-index.

    .heroImgContainer {
    background-image: url('.png');
    height: 400px;
    position: fixed;
    z-index: -1;
    

    }

    You also need to position the content section lower by 400px, so that it does not cover the image.

    .content {
    height: 1000px;
    background-color: black;
    position: relative;
    top: 400px;
    

    }

    Sample Code Pen: Static Hero with overlay