问题
I was stuck on this for a little bit and thought I\'d share this position: sticky
+ flex box 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 flex box 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
回答1:
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 only supported in Safari and Edge
.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;
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
回答2:
You can also try adding a child div to the flex item with the contents inside and assign position: sticky; top: 0;
to that.
That worked for me for a two column layout where the contents of the first column needed to be sticky and the second column appear scrollable.
回答3:
In my case,
One of the parent containers had this applied to it:
overflow-x: hidden;
You need to remove the above rule.
No parent element should have the above CSS rule applied to it. This condition applies to all parents up to (but not including) the 'body' element.
来源:https://stackoverflow.com/questions/44446671/my-position-sticky-element-isnt-sticky-when-using-flexbox