【问题标题】:position sticky automatic "top" position位置粘性自动“顶部”位置
【发布时间】:2015-03-03 18:43:33
【问题描述】:

有没有办法让即时贴考虑页面上的其他即时贴?

例如:

body {
  display: flex;
  min-height: 2000px;
  flex-direction: column;
}
#header {
  height: 40px;
  flex: 0 0 auto;
  position: sticky;
  top: 0;
  background: yellow;
}
#footer {
  flex: 0 0 auto;
  height: 20px;
}
#main {
  display: flex;
  flex: auto;
  background: blue;
}
#side {
  width: 200px;
  background: red;
}
#side > div {
  position: sticky;
  top: 0px;
}
<div id="header">header</div>
<div id="main">
  <div id="side">
    <div>side</div>
  </div>
  <div id="content">
    content
  </div>
</div>
<div id="footer">footer</div>

请注意,如果我向下滚动,标题将与侧边栏重叠,因为它们具有相同的 top 位置。

要解决这个问题,我必须让侧边栏的顶部位置采用标题高度的值

body {
  display: flex;
  min-height: 2000px;
  flex-direction: column;
}
#header {
  height: 40px;
  flex: 0 0 auto;
  position: sticky;
  top: 0;
  background: yellow;
}
#footer {
  flex: 0 0 auto;
  height: 20px;
}
#main {
  display: flex;
  flex: auto;
  background: blue;
}
#side {
  width: 200px;
  background: red;
}
#side > div {
  position: sticky;
  top: 40px;
}
<div id="header">header</div>
<div id="main">
  <div id="side">
    <div>side</div>
  </div>
  <div id="content">
    content
  </div>
</div>
<div id="footer">footer</div>

但是如果标题的高度可变怎么办?我可以告诉浏览器以某种方式放置便笺,以免它们与其他人重叠吗?

【问题讨论】:

  • 嗨,我在 2021 年面临同样的问题,你找到答案了吗?基本上我不想用js来更新动态header的top值

标签: css position overlap sticky


【解决方案1】:

我认为您需要为此使用 javascript。首先获取标题的高度,然后使用该值设置侧 div 的顶部位置。恐怕我不知道有任何纯 css 方式。

如果你使用 jQuery,它只是使用 .height() 方法,如果不是,你可以使用这个:

var clientHeight =        document.getElementById('myDiv').clientHeight;

var offsetHeight = document.getElementById('myDiv').offsetHeight;

offset 方法获取带有任何填充和边框的高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多