Raging Vids
Raging Vids

Reputation: 121

Background image increase size with scroll

I am trying to make the background image on a div change its scale as per the amount of page scrolled. Works well on desktop screens but on mobile screen, the BG image's height reduces and shrinks the image. This behaviour is apparent as I am trying to resize a sized cover image in % values. I have added a red background-color too to the div for better debugging. Any way to make it work flawlessly even on mob screens? The code is below as well as on Codepen.

HTML:

<main>
  <div class="section_1">
        <div class="welcome_message">            
            <div class="welcome_text">
                <p class="welcome">Welcome to</p>
                <h1>My</h1>
                <p class="tagline">DIRECTORY</p>
            </div>
        </div>
    </div>
</main>

CSS:

main{
min-height: 200vh;  
}

.section_1{
        position: relative;
        width: 100%;
        height: 90vh;
        background: red url(https://images.pexels.com/photos/9467294/pexels-photo-9467294.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260) 40% 10%/cover no-repeat;
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
}

.section_1 .welcome_message{
            width: 80%;
            min-height: 100%;
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;
            background: none;
            padding: 0 1rem 10rem 0;

            .welcome_text{    
                z-index: 3;
                // color: white;
                background-color: rgba(1, 55, 131, 0.5);
                border-bottom: 0.5rem solid white;
                padding: 1rem 2rem;
                border-end-start-radius: 2rem;
            }

            .welcome{
                color: white;
                font-weight: 400;
            }

            h1{
                font-size: 2rem;
                color: white;
                font-weight: 600;
                margin-block: -0.3em;
            }

            .tagline{
                color: white;
                font-weight: 400;
            }
  }

JS:

let bg = document.querySelector('body .section_1')

document.addEventListener('scroll', () => {        
  let x = window.pageYOffset
  bg.style.backgroundSize = (100 + x/10)+'% auto'
})

enter image description here

Upvotes: 0

Views: 1442

Answers (2)

allen
allen

Reputation: 92

Because you scroll all the way top again, bg.style.backgroundSize = 'auto 130%', The value of bg.style.backgroundSize should null.

Upvotes: 1

Abdelraouf Ferah
Abdelraouf Ferah

Reputation: 70

you almost made it instead of using auto use the calculated width and set the height to 100%

bg.style.backgroundSize = ''+(130 + x/10)+'% 100%'

Codepen :)

Upvotes: 1

Related Questions