Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

#header {
    position: sticky;
    width: 100vw;
    top: 0;
}
<app-header id="header"></app-header>

And that works fine, but I realised that if I use:

body {
  overflow-x: hidden;
}

That breaks sticky, and I need to set body overflow-x to hidden, how can I fix that, with only CSS solution, no JS solutions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
492 views
Welcome To Ask or Share your Answers For Others

1 Answer

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%;
}
<div class="overflow-x-hidden">
  <h1>I want to be sticky!</h1>
  
  <div class="tall"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...