CSS位置:粘性和溢出

时间:2016-06-10 15:53:06

标签: css css3 css-position

无法找到解决方案。基本上,我想要实现的是,如果内容比浏览器高度更多,那么position: sticky的元素会显示滚动条。

我不想使用position: fixed因为它会增加额外的疼痛。

以下是我希望它如何运作的示例:



.placeholder {
  height: 200vh;
  width: 50%;
  float: right;
}

.child {
  position: fixed;
  top: 0;
  bottom: 0;
  height: 100%;
  overflow-y: auto;
}

<div class="parent">
  <div class="placeholder"></div>
  <div class="child">
    some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br /> some long text
    <br />

  </div>
</div>
&#13;
&#13;
&#13;

Fiddle 1

以下是position: sticky overflow无法执行任何操作的示例:

&#13;
&#13;
.placeholder {
  height: 200vh;
  width: 50%;
  float: right;
}

.child {
  position: sticky;
  top: 0;
  bottom: 0;
  height: 100%;
  overflow-y: auto;
}
&#13;
<div class="parent">
  <div class="placeholder"></div>
  <div class="child">
    some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  some long text <br />
  
  </div>  
</div>
&#13;
&#13;
&#13;

Fiddle 2

任何解释/解决方案都表示赞赏。

确保在测试时使用Firefox

1 个答案:

答案 0 :(得分:13)

了解sticky元素首先被视为relative元素而然后一个fixed元素非常重要(请参阅{{3 }})。因此,您必须首先将其视为相对元素。如果给相对元素赋予100%的高度,那么除非其父元素具有已定义的高度,否则不会发生任何事情。

如果您希望粘性元素也有滚动条,则必须给它一个有意义的高度。我建议使用视口高度:

.child {
  position: sticky;
  top: 0;
  bottom: 0;
  height: 50vh;
  overflow-y: auto;
}

记录 - &#34;粘性&#34;在滚动期间元素变为fixed时,在FF或Safari中似乎没有按预期工作。我并不关心自己 - 只关注溢出问题。