CSS位置:粘滞和溢出

CSS position: sticky and overflow(CSS位置:粘滞和溢出)

本文介绍了CSS位置:粘滞和溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到此问题的解决方案。基本上,我试图实现的是,如果有比浏览器高度更多的内容,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>

Fiddle 1

以下是position: sticky的示例,其中overflow不执行任何操作:

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

.child {
  position: sticky;
  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>

Fiddle 2

欢迎任何解释/解决方案。

测试时确保使用Firefox

推荐答案

了解sticky元素首先被视为relative元素,然后然后被视为fixed元素(请参见MDN),这一点很重要。因此,您必须首先将其视为相对元素。如果为相对元素赋予100%的高度,则除非其父元素具有定义的高度,否则不会发生任何实际情况。

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

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

对于记录-"粘性"在FF或Safari中似乎没有像预期的那样工作,因为元素在滚动期间变为fixed。我不关心那件事--我只是专注于溢出问题。

这篇关于CSS位置:粘滞和溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:CSS位置:粘滞和溢出

基础教程推荐