How is horizontal position:sticky and width:auto related?

问题: 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 resul...

问题:

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?


回答1:

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> 

  • 发表于 2019-02-20 03:54
  • 阅读 ( 177 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除