Search code examples
htmlcsspositionparentsticky

CSS sticky position with nested elements


As far as I know, sticky position sticks to it's container before getting out of frame.

My problem is that I have some nested containers and a sticky element inside those, and want it to stick to it's grandparent.

One could suggest that I would bubble up my inner sticky child, but the problem is that it must stay inside it's parent because the parent is a flexbox that contains two elements, and I want one of those elements to be sticky while allowing the other to be scrolled away on overflow.

An example html:

<div class="main-container">
  <div class="inner-container">
    <div class="sticky">sticky child</div>
    <div class="non-sticky">non-sticky child</div>
  </div>
</div>

And the styling:

.inner-container {
  display: flex;
  flex-direction: row;
}

.sticky {
  position: sticky;
  top: 0;
}

Let's say that main-container is scrollable and inner-container is being scrolled through it.

I know there is no clear solution being supported by css, the question is if there is any trick to handle it.


Solution

  • Not sure what you're trying to do, but is this somewhere near what you need?

    .inner-container {
      display: flex;
      flex-direction: row;
    }
    
    .sticky {
      position: sticky;
      top: 0;
      width: 100px;
      height: 30px;
      justify-self: flex-start;
      background-color: green;
    }
    
    .non-sticky {
      background-color: blue;
      width: 100%;
      flex-grow: 5;
      flex-shrink: 5;
    }
    
    .main-container {
      height: 140px;
      overflow: scroll;
    }
    
    .inner-container {
      height: 300px;
    }
    <div class="main-container">
      <div class="inner-container">
        <div class="sticky">sticky child</div>
        <div class="non-sticky">non-sticky child</div>
      </div>
    </div>