1.table-cell实现水平垂直居中
.child{
vertical-align: middle;
display: table-cell;
text-align: center;
border:1px solid #666;
}
对table-cell元素设置百分比(如100%)的宽高值时无效的,但是可以将父元素设置display:table,再将父元素设置百分比宽高,子元素table-cell会自动撑满父元素。这就可以做相对于整个页面的水平垂直居中。代码示例如下:
.parent {
display: table;
width: 100%;
height: 100%;
}
2.父布局使用flex布局,使子div水平垂直居中
.parent {
-webkit-display:flex;
display:flex;
-webkit-align-items:center;
align-items:center;
-webkit-justify-content:center;
justify-content:center;
}
3.绝对定位方法:不确定当前div的宽度和高度
.parent {
height: 100%;
width: 100%;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
4.绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值
.parent {
height: 100%;
width: 100%;
position: relative;
}
.child {
width:600px;
height: 600px;
position: absolute;
left:50%;
top:50%;
margin-left:-300px;
margin-top:-300px;
}
5.绝对定位方法:绝对定位下top left right bottom 都设置0
.parent {
height: 100%;
width: 100%;
position: relative;
}
.child {
height: 100px;
width: 100px;
background-color: yellow;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
这是我们利用auto最常见的用法。通过分配auto元素的左右边距,它们可以平等地占据元素容器中的可用水平空间 - 因此元素将居中。