我的位置:使用flexbox时,粘性元素不粘性 [英] My position: sticky element isn't sticky when using flexbox

查看:81
本文介绍了我的位置:使用flexbox时,粘性元素不粘性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个问题上停留了一段时间,以为我会分享这个position: sticky + flexbox陷阱:

I was stuck on this for a little bit and thought I'd share this position: sticky + flexbox gotcha:

在将视图切换到Flex Box容器之前,我的粘性div一直工作良好,并且当将div包裹在flexbox父级中时,它突然变得不粘性.

My sticky div was working fine until I switched my view to a flex box container, and suddenly the div wasn't sticky when it was wrapped in a flexbox parent.

.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

推荐答案

由于flex box元素默认为stretch,因此所有元素的高度相同,无法滚动.

Since flex box elements default to stretch, all the elements are the same height, which can't be scrolled against.

在粘性元素上添加align-self: flex-start可以将高度设置为auto,从而可以滚动并固定它.

Adding align-self: flex-start to the sticky element set the height to auto, which allowed scrolling, and fixed it.

当前在所有主流浏览器中都支持> ,但是Safari仍在-webkit-前缀后面,以及Firefox以外的其他浏览器在position: sticky表方面存在一些问题.

Currently this is supported in all major browsers, but Safari is still behind a -webkit- prefix, and other browsers except for Firefox have some issues with position: sticky tables.

.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

这篇关于我的位置:使用flexbox时,粘性元素不粘性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆