我正在尝试使用 position: sticky
阻止元素滚动到 left: 0
。这在某些情况下工作正常,但我注意到如果元素宽度增加它会停止工作。例如以下作品:
#header {
position: sticky;
left: 0;
width: 50%;
background-color: #888;
}
#page {
height: 80vh;
width: 120vw;
background-color: #000;
}
<div>
<div id="header">
Where is my mind?
</div>
<div id="page">
</div>
</div>
但是,如果我将 header 元素的宽度增加到 100%
,它就会停止工作。
#header {
position: sticky;
left: 0;
width: 100%;
background-color: #888;
}
#page {
height: 80vh;
width: 120vw;
background-color: #000;
}
<div>
<div id="header">
Where is my mind?
</div>
<div id="page">
</div>
</div>
为什么会这样?有什么方法可以使用 position: sticky
来防止 header 元素在宽度为 100%
时滚动?在这种情况下,我不想使用 position: fixed
。
最佳答案
我现在明白发生了什么。问题在于浏览器处理 <div>
的宽度和高度的方式不同。 . auto
的默认值意味着 <div>
的宽度是100%
而高度由内容设置。如果内容比 100%
宽,然后在水平滚动时,粘性元素到达容器的末端 <div>
并且,由于它不能离开容器的范围,因此开始滚动。自容器 <div>
以来,在垂直滚动的相同情况下不会发生这种情况。默认情况下与内容一样高。
为防止这种情况发生,我们必须确保容器 <div>
与其内容一样广泛。这可以在大多数浏览器(不是 Edge 或 Explorer)中通过包含 width: max-content
来完成。在容器样式中。或者,如 mfluehr 的回答中所建议的那样,将 overflow: auto
创建一个与内容一样宽的新 block 格式化上下文。另一种选择是使用 display: inline-block
或 inline-flex
等导致容器<div>
使其宽度基于内容。
例如,使用其中两种技术,您可以创建适用于可垂直和水平滚动的页面的页眉、侧边栏和页脚:
body {
padding: 0;
margin: 0;
}
#app {
overflow: auto;
height: 100vh;
}
#header {
background: blue;
width: 100%;
height: 40px;
position: sticky;
top: 0;
left: 0;
z-index: 10;
color: white;
}
#sidebar {
position: sticky;
background: green;
width: 200px;
height: calc(100vh - 40px);
top: 40px;
left: 0;
color: white;
flex-grow: 0;
flex-shrink: 0;
}
#container {
display: inline-flex;
}
#content {
background: #555;
height: 200vh;
width: 200vw;
background: linear-gradient(135deg, #cc2, #a37);
flex-grow: 0;
flex-shrink: 0;
}
#footer {
background: #000;
height: 100px;
z-index: 100;
left: 0;
position: sticky;
color: white;
}
<div id="app">
<div id="header" ref="header">
Header content
</div>
<div id="container">
<div id="sidebar" ref="sidebar">
Sidebar content
</div>
<div id="content" ref="content">
Page content
</div>
</div>
<div id="footer" ref="footer">
Footer content
</div>
</div>
关于html - 当元素宽度增加时,位置粘性不适用于水平滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435232/