首页 > 解决方案 > CSS:如何使粘性元素不粘在页面顶部,而是粘在特定的像素或位置?

问题描述

图像1

我希望“+01”元素在有人滚动时跟随图像 div,但我不知道如何使它在到达页面顶部之前开始向下移动。有一个简单的解决方案吗?

标签: javascripthtmlcsspositionsticky

解决方案


如果我正确理解了您的问题,我认为您的目标可能是sticky职位。 更多信息

我根据您的图像为您制作了这个示例。希望能帮助到你:

body {margin:0; padding:0; background-color:orange;}
.container {
  position:relative;
  margin:0 auto;
  width:400px;
  margin-top:20px;
  margin-bottom:40px;
}
img {
  width:100%;
  display:block;
  margin-top:-40px;
}
.number {
  position:sticky;
  top:30px;
  margin-left:-40px;
  font-size:40px;
  color:#fff;
  text-shadow: 2px 2px 3px rgba(0,0,0,0.8);
  font-weight:bold;
  
}
<div class="container">
  <div class="number">
      +01
    </div>
    <img src="https://image.shutterstock.com/image-vector/greece-parthenon-sketch-600w-78255484.jpg" alt="">

</div>
<div class="container">
  <div class="number">
      +02
    </div>
    <img src="https://image.shutterstock.com/image-vector/greece-parthenon-sketch-600w-78255484.jpg" alt="">

</div>
<div class="container">
  <div class="number">
      +03
    </div>
    <img src="https://image.shutterstock.com/image-vector/greece-parthenon-sketch-600w-78255484.jpg" alt="">

</div>
<div class="container">
  <div class="number">
      +04
    </div>
    <img src="https://image.shutterstock.com/image-vector/greece-parthenon-sketch-600w-78255484.jpg" alt="">

</div>


推荐阅读