- Div垂直居中
- Flex 佈局
不考慮兼容老式瀏覽器的話,用Flex佈局簡單直觀一勞永逸:
parentElement{
display:flex;/*Flex佈局*/
display: -webkit-flex; /* Safari */
justify-content:center;/*要加上*//*水平居中 IE11*/
align-items:center;/*指定垂直居中*/
}
-
- 絕對定位+margin:auto
div絕對定位水平垂直居中【margin:auto實現絕對定位元素的居中】,
兼容性:,IE7及之前版本不支持
div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
-
- 絕對定位+margin負邊距
div絕對定位水平垂直居中【margin 負間距】,這或許是當前最流行的使用方法。
div{
width:200px;
height: 200px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
-
- 絕對定位+transform
div絕對定位水平垂直居中【Transforms 變形】
兼容性:IE8不支持;
div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:50%; /* 定位父級的50% */
top:50%;
transform: translate(-50%,-50%); /*自己的50% */
}