New title: My point is: the sticky properties of sticky elements are not preserved when using flexbox
P粉356128676
P粉356128676 2023-08-21 23:28:29
0
2
540
<p>I was stuck on this issue for a while and wanted to share this <code>position: sticky</code> flexbox issue:</p> <p>My sticky div, after switching to flexbox container view, is suddenly no longer sticky when wrapped in a flexbox parent element. </p> <p><br /></p> <pre class="brush:css;toolbar:false;">.flexbox-wrapper { display: flex; height: 600px; } .regular { background-color: blue; } .sticky { position: -webkit-sticky; position: sticky; top: 0; background-color: red; }</pre> <pre class="brush:html;toolbar:false;"><div class="flexbox-wrapper"> <div class="regular"> This is an ordinary box </div> <div class="sticky"> This is a sticky box </div> </div></pre> <p><br /></p> <p>JSFiddle display problem</p>
P粉356128676
P粉356128676

reply all(2)
P粉239164234

In my case, a parent container had the overflow-x: hidden; style applied, which would break the functionality of position: sticky. You need to remove this rule.

No parent element should have the above CSS rules applied. This condition applies to all parent elements up to (but not including) the 'body' element.

P粉311423594

Since the flexbox element defaults to stretch, all elements have the same height and cannot be scrolled.

Add align-self: flex-start to the sticky element and set the height to automatic, thereby achieving scrolling and fixing.

Currently, this is supported in all major browsers, but Safari still requires the -webkit- prefix, while other browsers except Firefox use position: sticky There are some problems with the form.

.flexbox-wrapper {
  display: flex;
  overflow: auto;
  height: 200px;          /* 不是必需的 -- 仅作为示例 */
}
.regular {
  background-color: blue; /* 不是必需的 -- 仅作为示例 */
  height: 600px;          /* 不是必需的 -- 仅作为示例 */
}
.sticky {
  position: -webkit-sticky; /* 适用于Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- 这是修复的地方 */
  background-color: red;  /* 不是必需的 -- 仅作为示例 */
}
<div class="flexbox-wrapper">
  <div class="regular">
    这是普通的盒子
  </div>
  <div class="sticky">
    这是粘性的盒子
  </div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template