Search code examples
htmlcsssticky

Why is my element not sticking to the left when using position sticky in css?


I want to fix an element to the top and left of the screen using position sticky when scrolling a large div either vertically or horizontally. Fixing to the top is working fine, but fixing to the left is not. This is my html page:

.sticky {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  top: 0;
}

.scroll-horizontally-and-vertically {
  width: 4000px;
  height: 2000px;
  background-color: lightblue;
}
<div>
  <div class="sticky">
    <h1>please stick to top and left</h1>
  </div>
  <div class="scroll-horizontally-and-vertically"></div>
</div>

I also tried using either top or left alone, with the same result. I must be missing something.

Why is the top position fixed, but not the left position? How should I fix the page to get the desired behaviour?


Solution

  • The sticky element is a block level element inside another block level so this one is already taking 100% width if its parent element and there is no room for a left sticky behavior.

    Add some border to better see:

    .sticky {
      position: -webkit-sticky;
      position: sticky;
      left: 0;
      top: 0;
      border:2px solid green;
    }
    
    .scroll-horizontally-and-vertically {
      width: 4000px;
      height: 2000px;
      background-color: lightblue;
    }
    <div style="border:2px solid red;">
      <div class="sticky">
        <h1>please stick to top and left</h1>
      </div>
      <div class="scroll-horizontally-and-vertically"></div>
    </div>

    The green box can only stick inside the red one and the lightblue element is overflowing. Addinline-block to sticky element (to remove the width 100% constraint) and to the parent element (so it grows with the lightblue element) and you will have the expected result

    .sticky {
      position: -webkit-sticky;
      position: sticky;
      left: 0;
      top: 0;
      border:2px solid green;
      display:inline-block
    }
    
    .scroll-horizontally-and-vertically {
      width: 4000px;
      height: 2000px;
      background-color: lightblue;
    }
    <div style="border:2px solid red;display:inline-block;">
      <div class="sticky">
        <h1>please stick to top and left</h1>
      </div>
      <div class="scroll-horizontally-and-vertically"></div>
    </div>