固定高度的垂直居中方式很好处理,但是我们在日常开发中,可能经常会碰到元素高度宽度不固定,但是我们要让他显示在屏幕正中间,比如最常见的弹出层处理,在高度不固定的情况下,如何保证弹出层垂直居中呢?
-
flex 布局
<style>
.index {
width: 400px;
height: 400px;
background: gray;
position: relative;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
display: flex;
align-items: center;
justify-content: center;
}
.index-dialog {
padding: 20px;
background: red;
text-align: center;
}
</style>
<div class="index">
<div class="index-dialog">2222222</div>
</div>
最后效果图如下:
-
CSS3中 transform + absolute 实现
<style>
.index {
width: 400px;
height: 400px;
background: gray;
position: relative;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
}
.index-dialog {
position: absolute;
padding: 20px;
background: red;
top: 50%;
transform: translateY(-50%);
left: 50%;
transform: translateX(-50%);
text-align: center;
}
</style>
<div class="index">
<div class="index-dialog">2222222</div>
</div>
最后效果图如下:
-
display: table
通过 display: table
和 display: table-cell
实现元素垂直居中
<style>
.index {
width: 400px;
height: 400px;
background: gray;
position: relative;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
display: table;
}
.index-dialog {
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
<div class="index">
<div class="index-dialog">
<img src="https://upload.jianshu.io/users/upload_avatars/14110538/2f118de3-606c-4da9-bc21-f66931c65792.png?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp" alt="">
</div>
</div>
-
利用伪类
::after
实现垂直居中
<style>
.index {
width: 400px;
height: 400px;
background: gray;
position: relative;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
text-align: center;
}
.index::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.index-dialog {
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
<div class="index">
<div class="index-dialog">222</div>
</div>
最后效果图如下:
网友评论