1

Having a horizontal sticky element I expected that width must not be auto for the sticky to work correctly.

So while this snipped works, removing width: 100px; will result in non-sticky behaviour.

#a {
  position: sticky;
  left: 0;
  background: red;
  width: 100px;
}

#b {
  /* this is to make a scrollbar */
  width: 3000px;
  background: blue;
}
<div id="a">a</div> 
<div id="b">b</div> 

Why is this so? I kind of assume that the browser needs the width to detect when the element leaves the viewport, but why does this not work for the auto calculated width in horizontal but in vertical mode?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Lux
  • 17,835
  • 5
  • 43
  • 73
  • possible duplicate of https://stackoverflow.com/q/53923923/8620333 / https://stackoverflow.com/q/52996574/8620333 – Temani Afif Feb 15 '19 at 19:25

1 Answers1

2

A stickily positioned element is still constrained within the boundaries of its containing block. When your element has auto width and is stickily positioned along the horizontal axis, it has no room left to stick before the rightmost edge of its containing block begins to push it along as its containing block gets scrolled out of view.

:root {
  border: medium solid fuchsia;
}

#a {
  position: sticky;
  left: 0;
  background: red;
  width: 100px;
}

#t:not(:checked) ~ #a {
  width: auto;
}

#b {
  /* this is to make a scrollbar */
  width: 3000px;
  background: blue;
}
<input type="checkbox" id="t" checked><label for="t"><code>width: 100px;</code></label>
<div id="a">a</div> 
<div id="b">b</div> 
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • I would probably say that we need to consider an inline-block container element to have what the OP expect. – Temani Afif Feb 15 '19 at 19:26
  • While this is not 100% what I've asked it helped me to answer the question. So when I dont specify the with, the element has the *same with then its parent* and so no sticky-space. – Lux Feb 16 '19 at 01:58
  • @Lux: The reason I didn't mention that was because I assumed you already knew that as the snippet you provided would have made it clear to you when you removed the width: 100px declaration. I assumed you were asking why the auto width was preventing sticky behavior, and I answered that fully. – BoltClock Feb 16 '19 at 02:08