我正在尝试使用网格创建一个网页,并且我希望当一行滚动过去时将左侧的一列粘贴在页面顶部,然后当该行中的其他内容消失时将其取消粘贴屏幕外。
到目前为止,我所做的就是为一行创建两个div,并将左侧的div设置为
position: sticky
和top: 0
,这样当滚动该行时,左侧的div保持在顶部。这适用于一行,但是当我向网格添加另一行时,两个 div 都保持附加到屏幕顶部。
.content {
display: grid;
grid-template-columns: 25vw 75vw;
grid-template-rows: auto auto;
}
.sidebar {
border-right: 1px solid lightgray;
border-left: 10px solid lightgray;
max-height: 100vh;
position: sticky;
top: 0;
}
.content {
flex-direction: column;
max-width: 70vw;
gap: 2em;
}
<div class="grid">
<div class="sidebar">
<h1>I want this div to be attached to the top of the screen while the row next to it is being scrolled through</h1>
</div>
<div class="content">
<h1>There is a lot of content here</h1>
<h1>Stretching the entire height of the screen</h1>
</div>
<div class="sidebar">
<h1>But when this row reaches the top, this overlaps with the first sidebar</h1>
</div>
<div class="content">
<h1>There is a lot of content here</h1>
<h1>Stretching the entire height of the screen</h1>
</div>
</div>
两个
sidebar
div 最终会重叠,我希望其中一个在到达这一点时从屏幕顶部“分离”。有没有办法在纯 CSS 中做到这一点,还是我必须使用 Javascript?
您可以为侧边栏指定背景颜色和固定高度。这并不优雅,但它完成了工作。
.content {
display: grid;
grid-template-columns: 25vw 75vw;
grid-template-rows: auto auto;
}
.sidebar {
border-right: 1px solid lightgray;
border-left: 10px solid lightgray;
background-color: white;
height: 120px;
position: sticky;
top: 0;
}
.content {
flex-direction: column;
max-width: 70vw;
gap: 2em;
}
<div class="grid">
<div class="sidebar">
<h1>I want this div to be attached to the top of the screen while the row next to it is being scrolled through</h1>
</div>
<div class="content">
<h1>There is a lot of content here</h1>
<h1>Stretching the entire height of the screen</h1>
</div>
<div class="sidebar">
<h1>But when this row reaches the top, this overlaps with the first sidebar</h1>
</div>
<div class="content">
<h1>There is a lot of content here</h1>
<h1>Stretching the entire height of the screen</h1>
</div>
</div>