I want .square
div to be always on top, so visually it seems like the next section with its own .square is sliding up and the .square stops exactly in the position of previous section’s square.
The following code does just that:
.scrollable {
border: 5px solid red;
position: relative;
.make-sticky {
position: relative;
height: 100vh;
padding: 20px;
box-sizing: border-box;
.line {
position: absolute;
left: 20px;
top: 0;
bottom: 0;
width: 2px;
background: black;
}
.square {
position: absolute;
left: 10px;
width: 20px;
height: 20px;
background: transparent;
border: 2px solid red;
top: 25%; /* Adjust this percentage based on your design */
z-index: 1;
}
p {
margin-top: 50vh; /* Center text vertically */
}
&.sticky-section {
position: -webkit-sticky;
position: sticky;
top: 0;
}
}
}
<div class="scrollable">
<section class="make-sticky --green" id="section1">
<div class="line"></div>
<div class="square"></div>
<p>Lorem ipsum dolor sit amet</p>
</section>
<section class="make-sticky --green" id="section2">
<div class="line"></div>
<div class="square"></div>
<p>Quod magni natus dignissimos</p>
</section>
<section class="make-sticky --white" id="section3">
<div class="line"></div>
<div class="square"></div>
<p>Quod magni natus dignissimos</p>
</section>
</div>
but the NEXT section covers the previous square when it "slides up".
There is no z-index set on any parent of my coding, so I wanted to use it, but it simply doesn’t work.
What can I do in order to make it work?
2
Answers
I’m not sure this is 100% what you are looking for, but it may get you close.
First of all,you don’t need
Z-index
at all for this. There is no.sticky-section
class in your code, addingposition:sticky
to it does nothing and needs to be removed, check the class names properly.Now you need to simply add
position:sticky
to the.square
class. Also, with position sticky you can not use left/right to position the square once you have given the top value where the element sticks. So, use margin to position it. That padding on the.make-sticky
section is causing a gap between the two squares. I have removed that so that the next square touches the previous square and pushes it upward before taking it’s place. Try removing the padding to see the difference in visuals.If this is not the desired result then please leave a comment or update your question for more clarification.