To achieve this effect, you can start by creating a separate container using the div
tag to hold all the squares or headers. This container should cover the entire scrollable area within your layout. Then, utilize the margin
property on each square to align it correctly with its corresponding section.
In order to ensure that the squares adjust automatically when the height of the sticky sections changes, custom CSS variables are utilized. By updating the height variable, the positioning of the squares will be maintained without manual adjustments.
Given that the squares are meant to be in sequence and overlap accordingly, there is no need for the use of z-index
. However, if you desired specific overlapping behavior, z-index could be applied as necessary.
Keep in mind that when using position: sticky, left/right positioning becomes invalid once the element becomes "stuck." Therefore, rely on the margin properties to position the square elements effectively.
:root {
--sticky-section-height: 100vh;
}
* {
box-sizing: border-box;
}
.scrollable {
border: 5px solid red;
position: relative;
}
.make-sticky {
height: var(--sticky-section-height);
box-sizing: border-box;
border-bottom: 1px solid green;
padding: 10px;
background-color: var(--clr);
position: relative;
}
.line {
position: absolute;
left: 20px;
top: 0;
bottom: 0;
width: 2px;
height: 100%;
background: black;
}
.sticky-container {
height: 100%;
width: 100%;
position: absolute;
top: 0;
z-index: 10;
border: 2px solid rgb(0, 21, 255);
}
.square {
position: sticky;
color: white;
top: 0px;
/* Margin used to position the element horizontally*/
margin-left: 10px;
margin-bottom: calc((var(--sticky-section-height) - 20px));
width: 20px;
height: 20px;
background: black;
border: 2px solid red;
/* Adjust this percentage based on your design */
}
p {
margin-top: 50vh;
/* Center text vertically */
}
<div class="scrollable">
<div class="sticky-container">
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>
<section class="make-sticky" style="--clr: green" id="section1">
<div class="line"></div>
<p>Lorem ipsum dolor sit amet</p>
</section>
<section class="make-sticky" style="--clr: orange" id="section2">
<div class="line"></div>
<p>Quod magni natus dignissimos</p>
</section>
<section class="make-sticky" style="--clr: cyan" id="section3">
<div class="line"></div>
<p>Quod magni natus dignissimos</p>
</section>
</div>