如何正确实现居中Modal的动态高度与滚动条适配?
实现自适应高度的居中Modal
问题出在你给#outer设置了height: 100%,这会强制它撑满max-height的上限,哪怕内容高度远小于这个值,导致内容少的时候Modal也占据全屏可用高度。
修改后的代码如下:
CSS代码
#outer { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); max-height: calc(100vh - 80px); display: inline-block; /* 让容器根据内容自适应高度 */ } #inner { background-color: #0000FF; color: #FFF; padding: 10px; max-height: inherit; /* 继承外层的最大高度限制 */ overflow-y: auto; /* 内容超出时显示垂直滚动条 */ } .content-item { margin-bottom: 50px; }
HTML代码(无需修改)
<html> <body> <div id="outer"> <div id="inner"> <div class="content-item" style="background-color: red">My Content</div> <div class="content-item">My Content</div> <!-- 可根据需要增减.content-item数量测试效果 --> <div class="content-item" style="background-color: yellow">My Content</div> </div> </div> </body> </html>
关键修改说明
- 移除
#outer的height: 100%,改用display: inline-block让容器高度贴合内部内容,同时保留max-height限制最大高度; #inner通过max-height: inherit继承外层的高度限制,配合overflow-y: auto,在内容超出时自动生成滚动条,内容较少时则无滚动条,高度自适应。
测试效果:
- 内容较少时,Modal高度跟随内容,保持屏幕居中;
- 内容高度超过
calc(100vh - 80px)时,内部容器出现滚动条,Modal整体高度被限制在最大范围内,依然居中。
内容的提问来源于stack exchange,提问作者Wagner Paz
相关产品推荐
相关产品推荐

