弹窗高度缩小时顶部内容被遮挡,如何解决?
弹窗顶部内容遮挡问题排查
我做了个弹窗,设置800px高度时显示正常,但改成600px这类小尺寸后,就算滚动条处于最顶部位置,顶部内容还是会被遮挡。
800px高度弹窗效果:
600px高度弹窗效果:
当前使用的CSS代码
.schedule { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #fff; overflow: auto; } .schedule .day { width: 100%; height: auto; background: rgba(0, 0, 0, 0.3); backdrop-filter: blur(10px); display: flex; flex-direction: column; margin-bottom: 10px; } .schedule .name { background: rgba(255,156,0,0.3); padding: 10px 0; text-align: center; } .schedule .item { display: flex; flex-direction: column; align-items: center; justify-content: space-between; padding: 10px 0; } .schedule .item span:nth-child(1) { color: #ff9c00; font-weight: 600; } .schedule .item span:nth-child(2) { color: #fff; font-size: 14px; font-weight: 300; }
PHP生成的HTML代码
<div class="schedule"> <div class="day"> <div class="name">Poniedziałek</div> <div class="item" style="background-color:"> <span>Anna</span> <span>Spacer w chmurach</span> <span>Od: <b>17:12</b> Do: <b>19:12</b></span> </div> <div class="item" style="background-color:"> <span>Marcin</span> <span>Kuferek z muzyką</span> <span>Od: <b>20:00</b> Do: <b>22:00</b></span> </div> </div> <div class="day"> <div class="name">Wtorek</div> </div> <div class="day"> <div class="name">Środa</div> </div> <div class="day"> <div class="name">Czwartek</div> </div> <div class="day"> <div class="name">Piątek</div> </div> <div class="day"> <div class="name">Sobota</div> <div class="item" style="background-color:"> <span>Monika</span> <span>test</span> <span>Od: <b>12:25</b> Do: <b>15:25</b></span> </div> <div class="item" style="background-color:"> <span>Maciek</span> <span>test</span> <span>Od: <b>17:20</b> Do: <b>20:20</b></span> </div> </div> <div class="day"> <div class="name">Niedziela</div> </div> </div>
问题排查与解决
问题原因
核心问题出在.schedule的justify-content: center属性上。当弹窗高度缩小后,flex容器会把内部内容垂直居中,而当内容高度超过容器时,overflow: auto产生的滚动条虽然能滚动,但顶部内容会被容器视口“切掉”——因为居中布局让内容整体向上偏移了一部分,导致最顶部的内容超出了容器可视区域的顶部。
这和Opera GX浏览器无关,是flex布局的特性导致的,其他浏览器也会出现同样问题。
解决方法
把.schedule的justify-content: center替换为justify-content: flex-start,让内容从容器顶部开始排列:
.schedule { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: flex-start; /* 替换原有的center属性 */ color: #fff; overflow: auto; }
如果需要弹窗整体在页面中居中,应该把居中逻辑放在弹窗的外层容器上,而非滚动内容的.schedule元素。比如给弹窗外层容器设置:
.popup-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
让弹窗本身居中,.schedule只负责内部内容的滚动与排列即可。
内容的提问来源于stack exchange,提问作者Ademn
相关产品推荐
相关产品推荐

