1、利用flex布局实现:
.content {
display: flex;
flex-direction: column; /*布局方向,flex-direction为row也可以实现居中*/
justify-content: center; /*竖直方向居中*/
align-items: center; /*水平居中*/
}
2、margin auto 法,脱离文本流
<style>
.content {
width: 200px;
height: 200px;
border: 1px solid #c3c3c3;
background-color: green;
position: relative;
}
.box {
width: 50px;
height: 50px;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
</style>
3、margin 负值法
.content {
width: 200px;
height: 200px;
border: 1px solid #c3c3c3;
background-color: green;
position: relative;
}
.box {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
top: 50%;
left: 50%;
margin-left: -25px; /* width的一半 */
margin-top: -25px; /* height的一半 */
}
4、transform方法:
.content {
width: 200px;
height: 200px;
border: 1px solid #c3c3c3;
background-color: green;
position: relative;
}
.box {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
top: 50%;
left: 50%;
transform: translate(-50%,-50%); /* 或者 transform: translateX(-50%) translateY(-50%)*/
}
5、利用table-cell的方法(未脱离文档流)实现垂直居中
设置父元素的display: table-cell, 并且vertical-align: middle
.content {
width: 200px;
height: 200px;
border: 1px solid #c3c3c3;
background-color: green;
display: table-cell;
vertical-align: middle;
}
.box {
width: 50px;
height: 50px;
background-color: red;
}