Search code examples
htmlcsscss-selectorsbackground-image

Background image is not working correctly


I am trying to replicate this site which is mostly working fine. But when I try to use ::before to apply a background image, no matter what I try, it doesn't work as I want.

Here is the code :

/* Section */
section {
    grid-area: section;
    border: 2px solid red;
}

section::before {
    content: "";
    background: linear-gradient(180deg, rgba(32, 33, 37, 1) 0%, rgba(32, 33, 37, 0) 64%), url(https://zoro.to/images/zoro-bg.jpg) no-repeat center;
    background-size: cover;
    border: 2px solid gold;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
}

.afterimg {
    display: flex;
    border: 2px solid blue;
}

#search {
    width: 50%;
    height: 50%;
}

#image {
    max-width: 50%;
    height: 100%;
}

#image img {
    height: auto;
    width: 100%;
}
<section>
    <div class="afterimg">
        <div id="search">
            search
        </div>
        <div id="image">
            <img src="https://zoro.to/images/zoro.png" alt="">
        </div>
    </div>
</section>

Which produces this result. But I was expecting it to look like this. I don't understand why the image covers the whole page instead of just the <section>. Any help would be appreciated.


Solution

  • @Heghar, please add position: relative; to the section. In general, section is position-inherit, so you have to add position-relative to the parent which is benchmark of the child, before you add position-absolute to the child. Hope it is helpful to you~.

    /* Section */
    section {
        grid-area: section;
        border: 2px solid red;
        position: relative;
    }
    
    section::before {
        content: "";
        background: linear-gradient(180deg, rgba(32, 33, 37, 1) 0%, rgba(32, 33, 37, 0) 64%), url(https://zoro.to/images/zoro-bg.jpg) no-repeat center;
        background-size: cover;
        border: 2px solid gold;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
    }
    
    .afterimg {
        display: flex;
        border: 2px solid blue;
    }
    
    #search {
        width: 50%;
        height: 50%;
    }
    
    #image {
        max-width: 50%;
        height: 100%;
    }
    
    #image img {
        height: auto;
        width: 100%;
    }
        <section>
            <div class="afterimg">
                <div id="search">
                    search
                </div>
                <div id="image">
                    <img src="https://zoro.to/images/zoro.png" alt="">
                </div>
            </div>
        </section>