Search code examples
htmlcssfixedjs-scrollintoview

Div should be fixed only inside other div


I just can't get it to work right:

I have some sections. Within one section is a div. And I want this div to be fixed as soon as it's visible and to stop being fixed when the user scrolls to next section. The div should then be stucked to the bottom of the section it's in.

I hope I can explain it in a right way.

Here is a little sketch to show what I mean

I want to work with position:fixed not with position:sticky because the second one doesn't work most of the time.

Thanks for your help!


Solution

  • Why wouldn't you wanna use sticky? here is an example that seems to do what you want

    section {
      width: 100%;
      height: 100vh;
      background: red;
    }
    
    section:nth-of-type(odd) {
      background: blue;
    }
    
    section div {
      position: sticky;
      top: 0;
      height: 100px;
      width: 100px;
      background: white;
      border: 1px solid black;
    }
    <div class="container">
      <section><div>Im sticky</div></section>
      <section><div>Im sticky</div></section>
      <section><div>Im sticky</div></section>
    </div>