【问题标题】:Why is my element not sticking to the left when using position sticky in css?为什么在css中使用位置粘性时我的元素不粘在左边?
【发布时间】:2019-08-11 18:11:12
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: html css sticky


    【解决方案1】:

    粘性元素是另一个块级内的块级元素,因此如果它的父元素已经占用了 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;
    }
    <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>

    绿色盒子只能贴在红色盒子里面,浅蓝色元素溢出来了。将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;
    }
    <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>

    【讨论】:

    • 这个答案帮助我检查了我的父元素。就我而言,父级有一个display: flexflex-direction: column,所以我必须使用align-self: end 将特定的子元素与我想要的位置对齐。谢谢
    【解决方案2】:

    Erit Vortstenbosch 欢迎加入社区。我已经检查了您的代码,它工作正常。 只需将 h1 标签的边距和内边距设置为 0。 这是修改后的代码sn-p。

    .sticky {
      position: -webkit-sticky; 
      position: sticky; 
      left: 0; 
      top: 0;
    }
    
    .scroll-horizontally-and-vertically {
      width: 4000px; 
      height: 2000px; 
      background-color: lightblue;
    }
    
    h1 {
      padding: 0;
      margin: 0;
    }
    <div>
      <div class="sticky">
      <h1>please stick to top and left</h1>
      </div>
      <div class="scroll-horizontally-and-vertically"></div>
    </div>

    【讨论】:

    • @ZohaibTariq。感谢您检查我的代码。不幸的是,填充/边距修复没有帮助。水平滚动时,h1 仍然滚动到窗口外。
    • @ErikVorstenbosch 欢迎您。我不知道为什么它不起作用我尝试了相同的代码并且它对我有用。这里是gif
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2021-02-16
    • 2019-02-28
    • 2017-11-04
    • 1970-01-01
    • 2019-03-30
    • 2017-11-10
    相关资源
    最近更新 更多