【问题标题】:Sticky element not working in nested flex container with overflow (safari)粘性元素在带有溢出的嵌套弹性容器中不起作用(野生动物园)
【发布时间】:2021-02-23 06:25:12
【问题描述】:

我在启用了overflow:auto 的嵌套弹性容器中遇到了一个粘性元素的奇怪问题。我希望粘性元素与第二个元素具有相同的高度,并且一旦滚动到阈值(top: 0),它也会粘在其包含元素的顶部。

请注意:该行为在 Chrome/Edge/Firefox 中正常,但在 Safari 中则不行。

据此,sticky 应该可以在带有前缀-webkit 的 Safari 中使用。 (https://caniuse.com/?search=sticky)

有什么好的方法可以在 Safari 中完成这项工作吗?

提前致谢。

.wrapper {
  height: 100px;
  background-color: red;
  display: flex;
}

.container {
  height: 200px;
  display: flex;
  overflow: auto;
  
}

.first {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  background-color: blue;
}

.second {
  background-color: yellow;
  height: 500px;
}
<div class="wrapper">
  <div class="container">
    <div class="first">Scroll down
    </div>
    <div class="second">Here</div>
  </div>
</div>

为遇到类似问题并想了解粘性的人提供有用的链接:

Link 1 on stackoverflow

Link 2 on stackoverflow

【问题讨论】:

    标签: css flexbox safari sticky


    【解决方案1】:

    这不是问题的完整答案,因为它涉及以一种可能不适合所有情况的方式更改 HTML,但如果我们将第一个和第二个 div 中的每一个放在它们自己的容器中,那么 Safari(在 iPad 上测试IOS 14) 符合预期。

    .wrapper {
      height: 100px;
      background-color: red;
      display: flex;
    }
    
    .container {
      height: 200px;
      display: flex;
      overflow: auto;
      
    }
    
    .first {
      position: sticky;
      position: -webkit-sticky;
      top: 0;
      background-color: blue;
    }
    
    .second {
      background-color: yellow;
      height: 500px;
    }
    <div class="wrapper">
      <div class="container">
        <div class="first">Scroll down</div>
        </div>
      <div class="container">
        <div class="second">Here</div>
        </div>
    </div>

    【讨论】:

    • 感谢您的意见。这会起作用,但不幸的是不适用于我的情况。我明确需要一个共同的父母溢出。
    • 我怀疑这一点,因此在我的回答中表达了谨慎。这是一个非常奇怪的错误,绝对是 Safari 中的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多