CSS位置元素在滚动容器内"固定"

Sig*_*oss 28 html css position

我想知道是否有人为此找到了解决方案?

我正在寻找一个解决方案,将元素附加到滚动容器的顶部

HTML:

<div class="container">
  <div class="header">title</div>
  <div class="element">......</div>
  ... (about 10-20 elements) ...
  <div class="element">......</div> 
</div>
Run Code Online (Sandbox Code Playgroud)

所有"元素"都有position:relative,

容器有以下CSS:

.container {
  position:relative;
  width:200px;
  height:400px;
  overflow-y:scroll;
}
Run Code Online (Sandbox Code Playgroud)

我希望标题保持在容器的顶部,独立于其滚动位置和滚动在下面的元素.

到目前为止的CSS:

.header {
  position:absolute; /* scrolling out of view :-( */
  z-index:2;
  background-color:#fff;
}
.element{
  position: relative;
}
Run Code Online (Sandbox Code Playgroud)

所有元素都是块元素,我不能将标题移动到容器之外.jquery在这一点上是没有选择的.

Ark*_*ana 21

我认为你的解决方案通过了position:sticky.似乎是这样,position:fixed但尊重他父母的相对位置.

不幸的是,这是一个实验性功能,仅在Chromium中受支持.您可以在此测试页面中查看更多详细信息.

我想到的纯css解决方案是标记的一点变化.您只能为"元素"设置容器,如下所示:

<div class="cont_elements">
      <div class="element">......</div>
      .....
</div>
Run Code Online (Sandbox Code Playgroud)

并将溢出物给予这个内部容器.现在,你的标题贴在上面.

这是一个有效的演示.

  • 但请注意,目前这不适用于Chrome,它可以在IOS中使用,但不适用于Android版Chrome.请参见caniuse.com/#feat=css-sticky (2认同)

Mad*_*iha 5

这种情况下的解决方案是将标题弹出到滚动元素之外:

<div class="header">title</div>
<div class="container">
    <div class="element">......</div>
    <div class="element">......</div>
</div>
Run Code Online (Sandbox Code Playgroud)

尽管如果可能的话你可能应该有更好的语义元素(只是在这里猜测):

<h3>title</h3>
<ul>
    <li>......</li>
    <li>......</li>
</ul>
Run Code Online (Sandbox Code Playgroud)


Rob*_*ben 5

jQuery UI 为此添加了一个position()实用程序方法,可以让您的生活更轻松.

$( "#someElement" ).position({
    of:  //Element to position against,
    my:  //which position on the element being positioned,
    at:  //which position on the target element eg: horizontal/vertical,
    offset:  // left-top values to the calculated position, eg. "50 50"
});
Run Code Online (Sandbox Code Playgroud)

绝对帮助了我.


wat*_*lea 5

这是我想出的解决方案position: sticky(不幸的是没有 IE):

https://codepen.io/waterplea/pen/JjjMXzR

这个想法是在滚动容器的顶部有一个 0 高度的粘性容器,所以它会粘住但不会推动下面的任何内容,然后将你的东西绝对放在里面。这样你有宽度但没有高度,所以你只能像我在我的例子中使用按钮那样从顶部定位一些东西。

编辑:找到了一种方法,使其具有 100% 的高度,而不是使用浮动将内容推送到下方。更新了代码笔。calc(100% - 1px)由于 Firefox 中的这个错误而不得不使用:https : //bugzilla.mozilla.org/show_bug.cgi?id=1612561