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