將元素垂直,水平居中分兩種情況:一個是元素尺寸固定,二是元素尺寸不固定
一.尺寸固定
方法1:定位 ,50%,margin負距
.box{
width: 400px;
height: 300px;
border: 2px solid black;
/* 把元素變成定位元素 */
position: absolute;
/* 元素距離上,左都為50% */
left: 50%;
top: 50%;
/* 讓元素的左外邊距,上外邊距為元素寬高的1/2 注意margin是負距*/
margin-top: -150px;
margin-left: -200px;
}
圖解:
方法2:四方為都為0 ,margin:auto
.box{
width: 400px;
height: 300px;
border: 2px solid black;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
圖解:
3 方法三,元素尺寸不固定
.box2 {
position: absolute;
left: 50%;
top: 50%;
/* 設置元素的相對於自身的偏移度為負50%(也就是元素自身尺寸的一半)*/
transform: translate(-50%, -50%);
}
4.方法四:使用偽元素 利用inline-block與vertical-align配合偽元素達到垂直居中
/* 背景左右居中 */
.dialog_container {
text-align: center;
position: absolute;
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.35);
}
/* 偽元素上下居中 */
.dialog_container:after {
display: inline-block;
width: 0;
height: 100%;
content: "";
vertical-align: middle;
}
/* 真正居中的元素 */
.dialog_box {
display: inline-block;
vertical-align: middle;
text-align: left;
border: 1px solid black;
}
補充:將元素水平居中比較簡單
1.塊級元素居中 margin 和width配合
2.內聯元素居中 給其父級元素加text-align:center