淡入淡出背景的顶部和底部与溢出y滚动属性与css只

pbpqsu0x  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(119)

下面的代码几乎完成了,但是当我向下滚动时,我被黄色和红色的::before/::after元素卡住了。
黄色和红色的元素应该是可见的所有时间,我向下/向上滚动
任何帮助的人吗?

*{
      box-sizing: border-box;
      
    }
    
    body{
      margin:0;
      padding: 80px 40px;
    }
    
    #container{
    
    margin: 0 auto;
    max-height: 300px;
    height: 100%;
    position: relative;
    overflow-y: scroll;
    
    }
    
    .images{
      border: 5px solid yellow;
      display: flex;
      flex-direction: column;
      gap: 20px;
      height: 100%;
      padding: 20px;
    
    }
    
    .img {
    
      height: 100px;
      border-radius5px;
    
    }
    
    #container::before,
    #container::after{
    
      content:'';
      position: absolute;
       
      height: 30px;
      width: 100%;
      
    
    }
    
    #container::before{
    
    top:0;
    background:yellow;
    
    }
    #container::after{
    
    bottom:0;
    background:red;
    }
<div id="container" style="border: 5px solid red;">
  <main class="images">
    <div class="img div_1" style="background: green;"></div>
    <div class="img div_2" style="background: green;"></div>
    <div class="img div_3" style="background: green;"></div>
    <div class="img div_4" style="background: green;"></div>
  </main>
</div>

也许我在position属性上做错了。我想我在css代码中缺少了一些小的调整。

dl5txlt9

dl5txlt91#

你需要使用sticky positioning

#container::before,
#container::after {
  position: sticky;
  display: block;
}
* {
  box-sizing: border-box;
}
    
body {
  margin: 40px;
}
    
#container {
  margin: 0 auto;
  max-height: 300px;
  height: 100%;
  position: relative;
  overflow-y: scroll;
  border: 5px solid black;
}
    
.images {
  border: 5px solid cyan;
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
  padding: 2em 20px;
}

.img {
  height: 100px;
  border-radius: 5px;
}

#container::before,
#container::after {
  content: ' ';
  position: sticky;
  height: 30px;
  width: 100%;
  display: block;
}

#container::before {
  top: 0;
  background: yellow;
}
 
#container::after {
  bottom: 0;
  background: red;
}
<div id="container">
  <main class="images">
    <div class="img div_1" style="background: green;"></div>
    <div class="img div_2" style="background: green;"></div>
    <div class="img div_3" style="background: green;"></div>
    <div class="img div_4" style="background: green;"></div>
  </main>
</div>

相关问题