如何使用position: sticky将元素固定在父容器顶部而非页面顶部?
要让banner相对其父组件.content固定,而非整个应用顶部,核心是让.content成为独立的滚动容器,这样position: sticky就会基于这个父容器生效。具体修改如下:
修改后的CSS代码
.header { display: flex; flex-grow: 1; margin: 0px 25px; height: 64px; background-color: blue; position: fixed; top: 0px; z-index: 999; width: 100%; box-sizing: border-box; /* 修正宽度计算,避免margin导致横向溢出 */ } .content { width: inherit; box-sizing: border-box; margin-top: 64px; /* 避开fixed定位的header,防止内容被遮挡 */ height: calc(100vh - 64px); /* 高度设为视口高度减去header高度 */ overflow: auto; /* 让content成为内部滚动容器 */ } .banner { position: sticky; top: 0px; z-index: 100; box-sizing: border-box; background-color: red; width: 100%; } .form { padding: 15px 24px 0; display: flex; flex-flow: wrap; width: 100%; height: 1000px; background-color: green; }
关键修改说明
- 给
.content设置height: calc(100vh - 64px),让它刚好填满header下方的视口区域(64px为header高度,可按需调整)。 - 添加
overflow: auto使.content成为独立滚动容器,此时banner的sticky定位会基于该父容器生效,滚动content时banner会固定在content顶部。 - 给
.content加margin-top: 64px,避免内容被fixed的header遮挡。 - 给
.header补充box-sizing: border-box,修正margin导致的宽度溢出问题。
内容的提问来源于stack exchange,提问作者user11631308
相关产品推荐
相关产品推荐

