Search code examples
cssgoogle-chromesticky

position:sticky ignoring right value in chrome


I have a very simple need: make and element sticky on the right side of the screen.

All works fine in Firefox, but in Chrome the right: 0 property is ignored. I said nevermind, I can achieve my goals by using left: calc(100% - 80px); but this is a lucky case, when I know the width of the sticky element.

However then I was baffled: while the workaround stated above works as expected (the elemtn sticks to the right), so does left: 100%;, so does left: 2000% for that matter, without triggering overflow (tested in Chrome and Firefox). I am clearly missing something. Maybe I don't understand left and right positioning of sticky elements, although there are clearly differences between Firefox and Chrome.

left: calc(100% - var(--element-width)) totally makes sense, but can anyone explain: why is right ignored and why is left: 100% and left: 2000% for that matter also working (i.e. it positions the element where I would expect right: 0 to position it, when it should clearly overflow.)

.wrapper{
  width:100%;
  position:relative;
}
.container{
  height: 2000px;  
}
.floater{
  position:sticky;
  height:200px;
  width:80px;
  background:red;
  top:200px;
  right:0;  
}
<div class="wrapper">
    <div class="container">
      <div class="floater">
        hei!
      </div>
    </div>
</div>


Solution

  • You are confusing between how absolute and fixed works compared to sticky.

    Sticky positioning can be thought of as a hybrid of relative and fixed positioning. A stickily positioned element is treated as relatively positioned until it crosses a specified threshold, ref

    right and left will define the offset only when the element can stick on scroll. They will never position the element to the right or the left of the container.

    Some examples:

    .box {
      border:2px solid;
      height:100px;
      margin:0 40px;
    }
    .box > div {
      position:sticky;
      height:100%;
      width:100px;
      background:red;
      right:20px;
      left:20px;
    }
    
    body {
      width:200vw;
    }
    a left sticky behavior
    <div class="box">
      <div></div>
    </div>
    I move the element to the right using margin and we have a right sticky behavior
    <div class="box">
      <div style="margin-left:auto;"></div>
    </div>

    You can clearly see that the position of the element is not defined by left or right . right and left are only defining the distance the element should keep from the screen edges when we scroll.

    Related questions for more details:

    Why bottom:0 doesn't work with position:sticky?

    If you specify `bottom: 0` for position: sticky, why is it doing something different from the specs?

    Why isn't position:sticky with left:0 working inside a scrollable container?