How to break out of position:sticky in a list of items?

Viewed 196

I have a list of items. As soon as the bottom item scrolls up to the rest and all of them have the same spacing, I want all of them to keep moving up together when I'm scrolling.

Right now they stack on top of each other before moving up.

Here's an example on codepen: https://codepen.io/xdth/pen/gOPBKNw

.block {
  height: 1500px;
}

.list {
  margin-top: 400px;
}

li {
  padding: 65px;
  font-size: 20px;
}

#one {
  position: sticky;
  top: 20vh;
}

#two {
  position: sticky;
  top: 30vh;
}
<div class="block">
  Scroll down
  <ul class='list'>
    <li id='one'>one</li>
    <li id='two'>two</li>
    <li id='three'>three</li>
  </ul>
</div>

How do I make them go up together without stacking?

1 Answers

You can approximate this using some negative margin:

.block {
  height: 800vh;
}

.list {
  margin-top:100vh;
}

li {
  padding: 65px;
  font-size: 20px;
  position: sticky;
}

#one {
  top: 10vh;
}
#two {
  top: 20vh;
  margin-bottom:-150px; /* 150px is an approximation of the height of the li */
}
#three {
  top: 30vh;
  margin-top:150px; /* the negation of the above one */
  margin-bottom:-300px; /* twice the size here */
}
<div class="block">
  Scroll down
  <ul class='list'>
    <li id='one'>one</li>
    <li id='two'>two</li>
    <li id='three'>three</li>
  </ul>
</div>

Related