Is there a way to adjust the background image of a div
so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image shrinks. This issue arises when trying to resize a cover image using percentage values. I have also added a red background color to the div for easier debugging. How can this be fixed to work seamlessly even on mobile screens? You can find the code snippet below or visit the full code 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'
})