【问题标题】:Position Sticky does not work inside container [duplicate]位置粘性在容器内不起作用[重复]
【发布时间】:2021-08-28 16:51:08
【问题描述】:

一旦用户滚动页面,我想让图像标题贴在视口的顶部,但它不起作用。非常感谢您的帮助,这是我的 HTML 和 CSS 代码:

 <div id="img-div">
      <img src="https://static.stacker.com/s3fs-public/styles/sar_screen_maximum_large/s3/Audrey%20Lead.png" id="image">
      <p id="img-caption"><strong>For beautiful eyes, look for the good in others; for beautiful lips, speak only words of kindness; and for poise, walk with the knowledge that you are never alone.<br><br>-Audrey Hepburn</strong></p>    
      </div>
html{
  width: 100vw;
}

body{
  width: 100%;
  margin: auto;
}

h1{
  position: absolute;
  z-index: 5;
}

#img-div{
  position: relative;
  height: 778px;
  width: 100%;
}

#image{
  background-repeat: no-repeat;
  height: 774px;
  width: 100%;
  object-fit: cover;
}


#img-caption{
  position: sticky;
  font-size: 19px;
  height: 9.5em;
  width: 21em;
  padding: 23px 13px 20px 23px;
  margin: 0;
  background-color: white;
  opacity: 70%;
  top: 0px;
  z-index: 5;
}

【问题讨论】:

    标签: css position


    【解决方案1】:

    问题是粘性位置出现在给定代码中,与包含元素相关,而不是与视口相关。

    这个 sn-p 将标题从该元素中取出,然后粘贴到视口的顶部。 (注意,为了让物体可滚动,本演示的主体高度为 500vh)。

    html {
      width: 100vw;
    }
    
    body {
      width: 100%;
      margin: auto;
      height: 500vh;
    }
    
    h1 {
      position: absolute;
      z-index: 5;
    }
    
    #img-div {
      position: relative;
      height: 778px;
      width: 100%;
    }
    
    #image {
      background-repeat: no-repeat;
      height: 774px;
      width: 100%;
      object-fit: cover;
    }
    
    #img-caption {
      position: sticky;
      font-size: 19px;
      height: 9.5em;
      width: 21em;
      padding: 23px 13px 20px 23px;
      margin: 0;
      background-color: white;
      opacity: 70%;
      top: 0px;
      z-index: 5;
    }
    <div id="img-div">
      <img src="https://static.stacker.com/s3fs-public/styles/sar_screen_maximum_large/s3/Audrey%20Lead.png" id="image">
    </div>
    <p id="img-caption"><strong>For beautiful eyes, look for the good in others; for beautiful lips, speak only words of kindness; and for poise, walk with the knowledge that you are never alone.<br><br>-Audrey Hepburn</strong></p>

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      相关资源
      最近更新 更多