Issue
I am creating a div which have an image and text flexed as a row. The desired effect I am trying to achieve is that when I scroll through the div, the text that is at the center of the div will move down while the image stays constant. I am using sticky position for the image to achieve this but there seems to be a problem in my approach. I am attaching part of my code below.
for reference this is the effect I want https://codepen.io/_catherinemc/pen/yKGvGM
.story3 {
position: relative;
top: 5rem;
align-items: center;
display: flex;
background-color: rgb(21, 0, 255);
height: 100vh;
}
.tft {
position: sticky;
}
.tft img {
width: 100%;
height: 100%;
}
.test {
position: relative;
top: 45rem;
}
<div>
<div class="story3">
<p class="header">Text of the div that will scroll down </p>
<div class="tft">
<img src="14.png" alt="">
</div>
</div>
</div>
<div class="test">
<p>Text below used for scroll </p>
</div>
Solution
The sticky property requires you to define either a "top", "left", "bottom", or "right" property as well.
document.addEventListener("DOMContentLoaded", function () {
const header = document.querySelector(".header");
const tft = document.querySelector(".tft");
const offset = tft.offsetHeight;
window.addEventListener("scroll", function () {
const scrollPosition = window.scrollY;
header.style.transform = "translateY(" + scrollPosition + "px)";
});
});
.story3 {
position: relative;
top: 5rem;
align-items: center;
display: flex;
background-color: rgb(21, 0, 255);
height: 100vh;
overflow-y: auto; /* container is scrollable */
}
.tft {
width: 50%;
}
.tft img {
width: 100%;
height: 100%;
object-fit: cover; /* Maintain aspect ratio of the image */
}
.header {
margin: 0; /* Remove default margin on paragraph */
}
.test {
position: relative;
top: 45rem;
}
<div class="story3">
<div class="tft">
<img src="14.png" alt="">
</div>
<p class="header">Text of the div that will scroll down </p>
</div>
<div class="test">
<p>Text below used for scroll </p>
</div>
Also ensure that the container is scrollable.
Answered By - Łukasz D. Mastalerz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.