Search code examples
cssscrollsticky

Scrolling with multiple sticky elements within the same parent


I'm trying to figure how the sticky position works with three elements within the same div. My problem is that the composition is working only on the bottom of the scroll and during the scroll, but not on top. How can I have the block start from the same composition as it is while scrolling and on the bottom?

The idea is the block of the three elements to always have the following composition and move together within the parent div #main:

  • White with height of 100px
  • 25px gap
  • Green with height of 40px
  • 0px gap
  • Red with height of 30px

#main {
    background: #ccc;
    height: 1000px;
    padding:100px;
}
#one,#two,#three {
  position:sticky;

}
#one{
  height: 100px;
  background: white;
  top:150px;
  margin-bottom: 95px;
  /*padding-bottom: 115px;
  margin-top:-150px;*/
  
}

#two{
  height:40px;
  background: green;
  top:275px;
  margin-bottom: 30px;
  /*padding-bottom: 50px;
  margin-top:-275px;*/
}

#three{
  height:30px;
  background: red;
  top:315px;
  
  /*padding-bottom: 20px;
  margin-top:-315px; */
}

#main-after, #main-before {
  background: black;
  height: 500px;
}
<div id="main-before">
</div>
<div id="main">
  <div id="one">one</div>
  <div id="two">two</div>
  <div id="three">three</div>
</div>
<div id="main-after">
</div>

Thank you for your help!


Solution

  • The solution is to sticky the #main and not the separate divs, so they behave as a block!