Home  >  Q&A  >  body text

New title: My point is: the sticky properties of sticky elements are not preserved when using flexbox

<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粉356128676P粉356128676397 days ago482

reply all(2)I'll reply

  • P粉239164234

    P粉2391642342023-08-22 13:49:33

    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.

    reply
    0
  • P粉311423594

    P粉3114235942023-08-22 13:20:07

    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>

    reply
    0
  • Cancelreply