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

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>

Tags:

Html

Css

Sticky