我的立场:使用 flexbox 时粘性元素不粘性

新手上路,请多包涵

我被困在这个问题上,并认为我会分享这个 position: sticky + flexbox gotcha:

我的粘性 div 工作正常,直到我将视图切换到 flex box 容器,突然 div 被包裹在 flexbox 父级中时没有粘性。

 .flexbox-wrapper {
  display: flex;
  height: 600px;
}
.regular {
  background-color: blue;
}
.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background-color: red;
}
 <div class="flexbox-wrapper">
  <div class="regular">
    This is the regular box
  </div>
  <div class="sticky">
    This is the sticky box
  </div>
</div>

JSFiddle 显示问题

原文由 bholtbholt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

由于弹性盒元素默认为 stretch ,所有元素的高度相同,无法滚动。

添加 align-self: flex-start 到粘性元素将高度设置为自动,允许滚动并修复它。

目前,所有主要浏览器都 支持 这一点,但 Safari 仍然落后于 -webkit- 前缀,除 Firefox 之外的其他浏览器在 position: sticky 表方面存在一些问题。

 .flexbox-wrapper {
  display: flex;
  overflow: auto;
  height: 200px;          /* Not necessary -- for example only */
}
.regular {
  background-color: blue; /* Not necessary -- for example only */
  height: 600px;          /* Not necessary -- for example only */
}
.sticky {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- this is the fix */
  background-color: red;  /* Not necessary -- for example only */
}
 <div class="flexbox-wrapper">
  <div class="regular">
    This is the regular box
  </div>
  <div class="sticky">
    This is the sticky box
  </div>
</div>

JSFiddle 显示解决方案

原文由 bholtbholt 发布,翻译遵循 CC BY-SA 4.0 许可协议

在我的例子中,其中一个父容器应用了 overflow-x: hidden; ,这将破坏 position: sticky 功能。您需要删除该规则。

任何父元素都不应应用上述 CSS 规则。此条件适用于(但不包括)’body’ 元素的所有父元素。

原文由 TheoPlatica 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题