1.利用transform (绝对定位方法:不确定当前div的宽度和高度)
.son {
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值
.son { width: 300px; height: 300px; background: red; position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -150px; }
3.绝对定位方法:绝对定位下top left right bottom 都设置0
.son {
width: 300px;
height: 300px;
background: red;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
4.flex布局方法:当前div的父级添加flex css样式
.son {
width: 300px;
height: 300px;
background-color: red;
}
.father {
display: flex;
height: 100vh;
align-content: space-around; /* 垂直居中, */
flex-wrap: wrap; /* 允许换行, */
justify-content: space-around; /* 左右居中 */
}
5.table-cell实现水平垂直居中: table-cell middle center组合使用
.father {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 100vh;
height: 100vh;
border: 1px solid #666;
}
.son {
display: inline-block;
height: 200px;
width: 200px;
background: yellow;
}