html结构:
<div class="class_name">
<div>垂直居中</div>
</div>
实现水平垂直居中的方法 :
1、
display:flexcss:
.class_name{
display: flex;
justify-content:center;
align-items:Center;
}
注意:display设置flex后,子元素均变为行级元素(即:div变为行级元素)
2、 绝对定位和负边距
css:
.class_name{
position:relative;
}
.class_name div{
position: absolute;
width:100px;
height: 50px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-25px;
text-align: center;
}
3、绝对定位和0
css:
.class_name{
position:relative;
}
.class_name div{
width: 50%;
height: 50%;
background: #000;
overflow: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
4、绝对定位和translate
css:
.class_name{
position:relative;
}
.class_name div{
position: absolute;
top:50%;
left:50%;
width:100%;
transform:translate(-50%,-50%);
text-align: center;
}
5、display:table-cell
css:
.class_name{
display: table-cell;
vertical-align: middle;
text-align: center;
}
6、display:inline-block
css:
.class_name{
text-align:center;
font-size:0;
}
.class_name div{
vertical-align:middle;
display:inline-block;
font-size:16px;
}
/**after用来占位*/
.class_name:after{
content:'';
width:0;
height:100%;
display:inline-block;
vertical-align:middle;
}
7、display:flex和margin:auto
css:
.class_name{
display: flex;
text-align: center;
}
.class_name div{
margin: auto;
}
效果展示: