CSS绝对定位问题:子元素溢出overflow:auto父容器且无法完整显示
解决绝对定位子元素溢出容器的问题
问题原因
你的left-popup是绝对定位元素,相对于父级popup-container(设置了position: relative)定位,而popup-container默认overflow: visible,导致left-popup超出其边界的部分会直接溢出到外部;再加上container的margin-left和滚动特性,最终造成部分内容无法完整显示。
解决方案
方案1:限制在popup-container内显示
给popup-container添加overflow: hidden,这样left-popup超出popup-container的部分会被裁剪,同时保留container的overflow: auto滚动特性:
<div class="container" style="height: 200px; overflow: auto; margin-left: 100px;"> <div class="popup-container" style="height: 300px; background: #ccc; position: relative; overflow: hidden;"> <div class="left-popup" style="position: absolute; height: 100px; width: 50px; background: #9C27B0; left: 0;"></div> </div> </div>
这个方案适合需要left-popup完全处于popup-container内部的场景,滚动container时,left-popup会随popup-container同步滚动。
方案2:让元素相对于container定位
如果希望left-popup在container范围内显示,而非受限于popup-container,可以给container添加position: relative,调整left-popup的定位基准:
<div class="container" style="height: 200px; overflow: auto; margin-left: 100px; position: relative;"> <div class="popup-container" style="height: 300px; background: #ccc;"> <div class="left-popup" style="position: absolute; height: 100px; width: 50px; background: #9C27B0; left: 0; top: 0;"></div> </div> </div>
这个方案下,left-popup会固定在container的指定位置,滚动container时不会跟随popup-container移动。
内容的提问来源于stack exchange,提问作者Mohamed SAHBANI
相关产品推荐
相关产品推荐

