gpt4 book ai didi

html - 剩余零的嵌套粘性元素不粘性

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:05 25 4
gpt4 key购买 nike

为什么我的 left: 0 嵌套粘性元素不粘附,而 top: 0 嵌套元素正常粘附?

.scroll {
width: 200px;
height: 200px;
border: 1px solid;
overflow: auto;
}

.container {
width: 600px;
height: 1000px;
}

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

.sticky-top {
position: sticky;
top: 0;
}
<div class="scroll">
<div class="sticky-top">sticky-top</div>
<div class="sticky-left">sticky-left</div>
<div class="container">
<div class="sticky-top">sticky-top-nested</div>
<div class="sticky-left">sticky-left-nested</div>
</div>
</div>

最佳答案

让我们添加一些边框,我们将清楚地看到发生了什么:

.scroll {
width: 200px;
height: 200px;
border: 1px solid;
overflow: auto;
}
.scroll > div {
border:2px solid green;
}

.container {
width: 600px;
height: 1000px;
border:2px solid red!important;
}
.container > div {
border:2px solid green;
}

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

.sticky-top {
position: sticky;
top: 0;
}
<div class="scroll">
<div class="sticky-top">sticky-top</div>
<div class="sticky-left">sticky-left</div>
<div class="container">
<div class="sticky-top">sticky-top-nested</div>
<div class="sticky-left">sticky-left-nested</div>
</div>
</div>

如您所见,嵌套的粘性元素的宽度都等于父元素的宽度(因为它们是 block 元素),因此左粘性元素没有任何粘性行为的空间1 因为它的 width:100% 与顶部的不同,它仍然可以粘住,因为它的高度小于父级高度。

对于非嵌套元素我觉得很清楚。


使元素inline-block 或减小宽度,您将有一个粘性行为:

.scroll {
width: 200px;
height: 200px;
border: 1px solid;
overflow: auto;
}
.scroll > div {
border:2px solid green;
}

.container {
width: 600px;
height: 1000px;
border:2px solid red!important;
}
.container > div {
border:2px solid green;
width:150px;
}

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

.sticky-top {
position: sticky;
top: 0;
}
<div class="scroll">
<div class="sticky-top">sticky-top</div>
<div class="sticky-left">sticky-left</div>
<div class="container">
<div class="sticky-top">sticky-top-nested</div>
<div class="sticky-left">sticky-left-nested</div>
</div>
</div>


1 A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.ref

在你的情况下,你总是遇到相反的边缘。

关于html - 剩余零的嵌套粘性元素不粘性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53923923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com