CSS Grid重叠元素固定定位:主内容滚动时装饰线固定不偏移
解决方案
你之前的方案没有生效是因为设置section滚动时没有同步修改它的高度,400vh的高度会超出外层容器的视口范围,滚动时会带动整个Grid容器一起位移,自然就会带跑装饰线。
只需要修改两处CSS配置即可实现预期效果:
- 给
body添加overflow: hidden,禁用页面全局滚动 - 修改
.section的样式:将原有高度400vh改为100vh,新增overflow-y: auto让其内部的文本内容可独立滚动,四个装饰线作为外层Grid容器的子元素会固定在原位置不跟随内容滚动。
如果需要隐藏滚动条提升视觉效果,可以额外给.section添加滚动条隐藏样式。
修改后的CSS代码
*, ::before, ::after { box-sizing: border-box; } body { margin: 0; line-height: 2.5; color: #f1f1f1; overflow: hidden; /* 新增:禁用全局滚动 */ } body .container { display: grid; grid-template-columns: repeat(5, 1fr); grid-template-rows: repeat(6, 1fr); grid-column-gap: 0px; grid-row-gap: 0px; height: 100vh; } body .section { grid-area: 1/1/7/6; height: 100vh; /* 修改:从400vh改为100vh,和外层容器等高 */ overflow-y: auto; /* 新增:内部内容独立滚动 */ background: linear-gradient(to bottom, #0F2740, #12355A, #224A73, #4985C1); } /* 可选:隐藏滚动条 */ body .section::-webkit-scrollbar { display: none; } body .section { -ms-overflow-style: none; scrollbar-width: none; } body .section .sub-section { display: grid; height: 100vh; } body .section .sub-section .words { place-self: center; } body .top-left { grid-area: 1/1/4/3; justify-self: start; align-self: center; } body .top-left .deco-line { border: 3px dashed rgba(255, 255, 255, 0.3); width: 250px; } body .top-right { grid-area: 1/4/4/6; justify-self: center; align-self: stretch; } body .top-right .deco-line { border: 3px dashed rgba(255, 255, 255, 0.3); height: 200px; } body .bottom-left { grid-area: 4/1/7/3; justify-self: center; align-self: end; } body .bottom-left .deco-line { border: 3px dashed rgba(255, 255, 255, 0.3); height: 250px; } body .bottom-right { grid-area: 4/4/7/6; justify-self: end; align-self: center; } body .bottom-right .deco-line { border: 3px dashed rgba(255, 255, 255, 0.3); width: 250px; }
HTML代码无需做任何修改。
内容的提问来源于stack exchange,提问作者CyberCatHK
相关产品推荐
相关产品推荐

