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

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

问题描述

我被这个问题困住了一段时间,并想我会分享这个position:sticky + flexbox gotcha:

我的粘性 div 工作正常,直到我将视图切换到 flex box 容器,当它被包裹在 flexbox 父级中时,div 突然变得不粘了.

.flexbox-wrapper {显示:弹性;高度:600px;}.常规的 {背景颜色:蓝色;}.sticky {位置:-webkit-sticky;位置:粘性;顶部:0;背景颜色:红色;}

<div class="regular">这是普通的盒子

<div class="sticky">这是粘箱

JSFiddle 显示问题

解决方案

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

>

在sticky元素中添加align-self:flex-start,设置高度为auto,允许滚动,并修复.

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

.flexbox-wrapper {显示:弹性;溢出:自动;高度:200px;/* 没有必要——仅举例 */}.常规的 {背景颜色:蓝色;/* 没有必要——仅举例 */高度:600px;/* 没有必要——仅举例 */}.sticky {位置:-webkit-sticky;/* 对于 Safari */位置:粘性;顶部:0;align-self: flex-start;/* <-- 这是修复 */背景颜色:红色;/* 没有必要——仅举例 */}

<div class="regular">这是普通的盒子

<div class="sticky">这是粘箱

JSFiddle 显示解决方案

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

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 showing the problem

解决方案

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

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

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 showing the solution

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆