So in an HTML document I have two DIVs side by side, each with a different height. When the user starts scrolling down, both DIVs should start scrolling at the same time, as you would expect. When the end of the shorter DIV is reached, it should stick to the bottom of the viewport until the end of the taller DIV is reached. The page should then continue to scroll "normally". Here is the starting point:
.parent {
display: flex
}
.child {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.left {
background: lightblue;
height: 200vh;
}
.right {
background: lightcoral;
height: 120vh;
}
<div class="parent">
<div class="child left">
<div>Top</div>
<div>Bottom</div>
</div>
<div class="child right">
<div>Top</div>
<div>Bottom</div>
</div>
</div>
After fiddling around for some time, I can only achieve the exact opposite of what I try to accomplish:
.parent {
display: flex
}
.child {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.left {
background: lightblue;
height: 200vh;
}
.right {
background: lightcoral;
height: 120vh;
position: sticky;
top: 0;
}
<div class="parent">
<div class="child left">
<div>Top</div>
<div>Bottom</div>
</div>
<div class="child right">
<div>Top</div>
<div>Bottom</div>
</div>
</div>
Any help would be appreciated.
2
Answers
You could indeed consider using
position: sticky
, but set thetop
offset to20vh
, which would be the difference in height of the element and the viewport height:Derived this from @Wongjn’s great solution, using Javascript to calculate the
top
values for the child divs.