如何在居中的div上启用滚动?高度是恐怖的,所以我无法宣布它。
代码如下,在某些情况下可能不需要滚动,因为内容不足以满足要求。
div必须垂直居中(当它的高度小于视口高度时)和水平居中。
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
display: table;
}
.modal-wrapper {
display: table-cell;
vertical-align: middle;
padding: 0 25px;
}
.modal-container {
max-width: 600px;
margin: auto auto;
padding: 15px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
}

<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
</div>
</div>
&#13;
我的另一个解决方案是:
.modal-mask {
position: relative;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
}
.modal-wrapper {
position: absolute;
top: 0;
bottom: 0;
right:0;
left:0;
margin: auto;
padding: 0 25px;
}
.modal-container {
max-width: 600px;
margin: auto auto;
padding: 15px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
}
&#13;
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
This needs scroll<br>
</div>
</div>
&#13;
这个问题是当高度低于视口时容器没有垂直居中
答案 0 :(得分:2)
只需添加以下代码即可。希望它可以帮到你
.modal-container {overflow-y: auto; max-height: 100vh;}