参考地址:https://css-tricks.com/centering-css-complete-guide/
- margin:auto + 绝对定位 = 水平垂直居中(IE7及之前版本不能兼容)
div {
width: 100px;
height: 100px;
background: red;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
2.margin负间距 + 绝对定位 = 水平垂直居中(比较实用,适用与宽高已知)
div {
width: 100px;
height: 100px;
background: red;
position:absolute;
left:50%;
top: 50%;
margin-left:-50px;
margiin-top:-50px;
}
3.transform + 绝对定位 = 水平垂直居中(同方法二类似,适用与宽高未知)
div {
width: 100px;
height: 100px;
background: red;
position:absolute;
left:50%;
top: 50%;
transform: translate(-50%,-50%);
}
4.不定宽高水平垂直居中(flex布局实现~)
.parent {
height:600px;
display:flex;
justify-content:center;
align-items:center;
}
.parent>.child {
width: 100px;
height: 100px;
background: red;
}
5.grid布局快速实现
body, html {
height: 100%;
display: grid;
}
span { /* thing to center */
width:100px;
height:100px;
background-color:red;
margin: auto;
}