【问题标题】:How to stop a sticky element at the end of parent element如何在父元素末尾停止粘性元素
【发布时间】:2018-03-24 14:50:16
【问题描述】:

我有一个包含内容列和粘性侧边栏的布局。向下滚动页面我需要将侧边栏停在内容列的末尾。

这里是我使用的 HTML 和 CSS:

<div class="container">
  <div class="content">Content</div>
  <div class="sidebar">Sidebar (sticky)</div>
  <div style="clear:both"></div>
</div>


.content{
  float: right;
  width: 80%;
  margin-left: 20%;
}

.sidebar {
  float: left;
  width: 20%;
  position: -webkit-sticky;
  position: sticky;
  bottom: 30px;
}

同样在https://codepen.io/anon/pen/awNorj

我哪里错了?

【问题讨论】:

  • 您不能在网页上放置任何内容而不将其插入 DOM,所以我不明白您的问题,但您需要在此处发布您的标记,而不是 codepen,它可以更改或明天消失,将来不会帮助任何人:stackoverflow.com/help/mcve
  • 你能解释一下你对 DOM 的意思吗?也许截图会有所帮助。我没有看到您提到的“在右栏的末尾”效果。
  • 伙计们,这是他想要的行为i.imgur.com/NTVo5ro.png,但他却得到了这个i.imgur.com/M80qLWU.png
  • @RickyDam 啊,说清楚了。谢谢。
  • @RickyDam 就是这样!谢谢。无论如何,我刚刚更新了问题以使其更清楚

标签: css sticky


【解决方案1】:

您最初的问题是 css 技巧适用于顶部元素,但不适用于底部元素。因为技巧依赖于左上角的位置。要使用左下角执行此操作,您需要知道侧边栏的高度。

使用置顶元素,您可以:

  • 将侧边栏 div 放在首位
  • 然后是你的内容 div
  • 最后设置您的侧边栏float:left,以便容器根据内容调整其高度

演示:https://jsfiddle.net/1owyqtcn/1/

使用粘性底部元素float:left 技巧不起作用:它会使您的侧边栏溢出底部的容器。

演示:https://jsfiddle.net/d1byrhp6/4/


如果您不知道侧边栏的高度。


一种方法可以是使用负边距左技巧:将侧边栏 div 放入内容 div 并将其显示在外面。侧边栏和内容现在都对齐了。但是侧边栏在内容中留下了空白。

.content{
  background: purple;
  width: 80%;
  margin-left: 20%;
}

.sidebar {
  position: sticky;
  width: 25%; /* Adjust: 25% of 80% of container is 20% of container */
  background: #ff6347;
  bottom: 30px;
  margin-left: -25%;
}

演示:https://jsfiddle.net/zg9g3134/


如果您知道侧边栏的高度。


另一种方法是使用负边距顶部技巧来抑制高度,而不是float: left

.content{
  background: purple;
  width: 80%;
  margin-left: 20%;
}

.sidebar {
  height: 200px;
  overflow-y: hidden;
  margin-top: -200px;
  position: sticky;
  width: 20%;
  background: #ff6347;
  bottom: 30px;
}

演示:https://jsfiddle.net/rLs8dLba/2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2015-04-17
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多