在CSS中使用粘滞位置时,为什么我的元素不粘在左侧? [英] Why is my element not sticking to the left when using position sticky in css?
问题描述
当垂直或水平滚动大div时,我想使用位置固定功能将元素固定在屏幕的顶部和左侧.固定在顶部可以正常工作,但固定在左侧则不能. 这是我的html页面:
I want to fix an element to the top and left of the screen using position sticky when scrolling a large div either vertically or horizontally. Fixing to the top is working fine, but fixing to the left is not. This is my html page:
.sticky {
position: -webkit-sticky;
position: sticky;
left: 0;
top: 0;
}
.scroll-horizontally-and-vertically {
width: 4000px;
height: 2000px;
background-color: lightblue;
}
<div>
<div class="sticky">
<h1>please stick to top and left</h1>
</div>
<div class="scroll-horizontally-and-vertically"></div>
</div>
我也尝试使用顶部或单独使用,结果相同. 我一定很想念东西.
I also tried using either top or left alone, with the same result. I must be missing something.
为什么顶部位置固定,而左侧位置却不固定? 我应该如何修复页面以获得所需的行为?
Why is the top position fixed, but not the left position? How should I fix the page to get the desired behaviour?
推荐答案
sticky元素是另一个块级中的一个块级元素,因此,如果其父元素且没有剩余空间,则此粘性层已采用100%的宽度粘性行为.
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>
绿色框只能粘在红色框内,而浅蓝色元素正溢出.将inline-block
添加到粘性元素(以消除宽度100%约束)和父元素(以随lightblue元素增长),您将获得预期的结果
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>
这篇关于在CSS中使用粘滞位置时,为什么我的元素不粘在左侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!