display: flex parent中的Sticky子元素



我想让我的.sidebarflex元素在滚动时具有粘性但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属性,所以它不会隐藏在标题下)

相关内容

  • 没有找到相关文章

最新更新