CSS sticky position with nested elements

时间:2018-12-03 13:23:48

标签: html css position parent sticky

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.

1 个答案:

答案 0 :(得分:0)

不确定要执行的操作,但这是否在您需要的位置附近?

.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>

相关问题