我想让我的.sidebar
flex元素在滚动时具有粘性但position: sticky; top: 0;
不工作
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
}
header {
width: 100%;
height: 100px;
background-color: blue;
opacity: 0.5;
position: sticky;
z-index: 100;
top: 0;
}
.container {
display: flex;
gap: 2rem;
position: relative;
}
.sidebar {
position: sticky;
top: 0;
}
.main {
display: flex;
gap: 2rem;
flex-direction: column;
}
.main div {
width: 300px;
aspect-ratio: 1 / 1;
background-color: red;
}
<div class="root">
<header></header>
<div class="container">
<div class="sidebar">
<p>Sidebar</p>
<button>Upload image</button>
</div>
<div class="main">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
问题是align-items
的默认属性是normal
(在这种情况下像stretch
一样),因此.sidebar
元素采用所有可用的高度,不能有"粘性效果"。
您可以通过将.container
元素的align-items
属性更改为flex-start
来实现粘贴效果,如下所示:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
}
header {
width: 100%;
height: 100px;
background-color: blue;
opacity: 0.5;
position: sticky;
z-index: 100;
top: 0;
}
.container {
display: flex;
align-items: flex-start; /* <- ADD THIS */
gap: 2rem;
position: relative;
}
.sidebar {
position: sticky;
top: 100px;
}
.main {
display: flex;
gap: 2rem;
flex-direction: column;
}
.main div {
width: 300px;
aspect-ratio: 1 / 1;
background-color: red;
}
<div class="root">
<header></header>
<div class="container">
<div class="sidebar">
<p>Sidebar</p>
<button>Upload image</button>
</div>
<div class="main">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>
</div>
</div>
(注意,我还改变了.sidebar
元素的top
属性,所以它不会隐藏在标题下)