fixed定位模态框内容溢出容器问题及解决方案
解决fixed模态框内内容溢出容器的问题
我之前四处找这个问题的解决方案,试了好几种都不适用我的场景——我有个设置了position: fixed的模态框,里面.content的内容总是会溢出.modal-container容器。一开始我临时给<h1>加了超大的margin-top来凑活,但这明显不是个理想的办法。
补充说明:之前漏说了,我试过在所有div层级都加overflow: scroll或者overflow: auto,但完全没效果。
最终解决方案
感谢Zohir的帮忙,下面是更新后的.content类代码,分享给遇到同类问题的开发者参考:
.content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); max-height: 100%; max-width: 100%; overflow: auto; }
⚠️ 注意:.content的父元素(也就是.modal-content)需要设置为position: relative。
原问题代码
下面是我最开始的代码:
CSS代码
.modal-container { position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; } .modal-content { display: flex; justify-content: center; align-items: center; width: 90vw; height: 90vh; } .content { display: flex; flex-direction: column; align-items: center; justify-content: center; }
HTML代码
<div class="modal-container"> <div class="modal-content"> <div class="content"> <h1></h1> <form></form> </div> </div> </div>
内容的提问来源于stack exchange,提问作者HPJM
相关产品推荐
相关产品推荐

