位置粘性自动“顶部”位置

Elf*_*lfy 6 css position sticky overlap

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

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

请注意,如果我向下滚动标题将与侧边栏重叠,因为它们具有相同的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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

但是如果标题的高度可变呢?我可以告诉浏览器以某种方式定位便签,以免它们与其他人重叠吗?

小智 1

我认为你需要为此使用 javascript。首先获取标题的高度,然后使用该值设置侧边 div 的顶部位置。恐怕我不知道有任何纯 css 方法可以做到这一点。

如果您使用 jQuery,则只需使用 .height() 方法,如果没有,您可以使用以下方法:

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

var offsetHeight = document.getElementById('myDiv').offsetHeight;
Run Code Online (Sandbox Code Playgroud)

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