在 css 中使用位置粘性时,为什么我的元素不粘在左边?

Eri*_*sch 8 html css sticky

我想在垂直或水平滚动大 div 时使用位置粘性将元素固定到屏幕的顶部和左侧。固定到顶部工作正常,但固定到左侧则不行。这是我的 html 页面:

.sticky {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  top: 0;
}

.scroll-horizontally-and-vertically {
  width: 4000px;
  height: 2000px;
  background-color: lightblue;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <div class="sticky">
    <h1>please stick to top and left</h1>
  </div>
  <div class="scroll-horizontally-and-vertically"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用 top 或 left ,结果相同。我肯定错过了什么。

为什么顶部位置固定,而不是左侧位置?我应该如何修复页面以获得所需的行为?

Tem*_*fif 9

粘性元素是另一个块级内的块级元素,因此如果其父元素没有空间用于左粘性行为,则该元素已经占据 100% 的宽度。

添加一些边框以更好地查看:

.sticky {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  top: 0;
  border:2px solid green;
}

.scroll-horizontally-and-vertically {
  width: 4000px;
  height: 2000px;
  background-color: lightblue;
}
Run Code Online (Sandbox Code Playgroud)
<div style="border:2px solid red;">
  <div class="sticky">
    <h1>please stick to top and left</h1>
  </div>
  <div class="scroll-horizontally-and-vertically"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

绿色的盒子只能粘在红色的盒子里面,淡蓝色元素溢出。添加inline-block到粘性元素(删除宽度 100% 约束)和父元素(因此它与浅蓝色元素一起增长),您将获得预期的结果

.sticky {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  top: 0;
  border:2px solid green;
  display:inline-block
}

.scroll-horizontally-and-vertically {
  width: 4000px;
  height: 2000px;
  background-color: lightblue;
}
Run Code Online (Sandbox Code Playgroud)
<div style="border:2px solid red;display:inline-block;">
  <div class="sticky">
    <h1>please stick to top and left</h1>
  </div>
  <div class="scroll-horizontally-and-vertically"></div>
</div>
Run Code Online (Sandbox Code Playgroud)