body { overflow-x: hidden; } breaks position: sticky

后端 未结 3 1870
悲哀的现实
悲哀的现实 2020-12-03 20:53

I have an element that I am making sticky with position sticky:

#header {
    position: sticky;
    width: 100vw;
            


        
3条回答
  •  执念已碎
    2020-12-03 21:52

    UPDATE:

    This has been successfully tested on Safari v12.0.2, Firefox v64.0, and Chrome v71.0.3578.98

    Added position: -webkit-sticky; for Safari.


    Unfortunately the spec is not too clear about the implications of overflow-x: hidden; on position sticky, but there is a way to fix this. Thankfully there is an issue to hopefully fix this: https://github.com/w3c/csswg-drafts/issues/865.

    The simple solution is to remove or unset overflow-x: hidden; from every ancestor of the element you want to have position: sticky;. Then you can have overflow-x: hidden; on the body and it will work!

    Also double check that you don't have overflow set on both the body and html tags which I posted about more in depth here: https://stackoverflow.com/a/54116725/6502003

    Here is a pen if you want to play around with it: https://codepen.io/RyanGarant/pen/REYPaJ

    /* 
      Try commenting out overflow on body style and uncommenting
      overflow on .overflow-x-hidden class and you will see 
      position sticky stop working!  
    */
    
    body {
      overflow-x: hidden;
    }
    
    .overflow-x-hidden {
    /*   overflow-x: hidden; */
      border: 1px solid blue;
    }
    
    h1 {
      background: palevioletred;
      color: #fff;
      position: -webkit-sticky;
      position: sticky;
      top: 0;
    }
    
    .tall {
      background: linear-gradient(to bottom, paleturquoise, white);
      height: 300vh;
      width: 100%;
    }

    I want to be sticky!

提交回复
热议问题