絕對定位;
利用父元素相對定位和子元素絕對定位進行水平垂直居中,根據(jù)是否知道子元素寬高肢娘,使用數(shù)值或者百分比的方式進行定位
1.通過設(shè)置四向為0和margin: auto實現(xiàn)呈础。
.father{width:100px;height:100px;background-color: grey;position: relative;}
.child{width:50px;height:20px;background-color: red;
position: absolute;left:0;right:0;top:0;bottom:0;margin: auto;}
2.通過設(shè)置left和top使child左上角位置移動到中間,然后再移動自身寬高一般使child中心至中間橱健。未知寬高元素水平垂直居中
.father{width:100px;height:100px;background-color: grey;position: relative;} ?.child{width:50px;height:20px;background-color: red;position: absolute;left:50%;top:50%;margin: -10px-25px;}
.father{width:100px;height:100px;background-color: grey;position: relative;}
.child{width:50px;height:20px;background-color: red;position: absolute;left:50%;top:50%;transform:translate(-50%, -50%);}
總結(jié)
這幾種方法使用了絕對定位而钞,margin或者transform來使子元素水平垂直居中,根據(jù)是否知道具體寬高來使用margin或者transform拘荡。
彈性盒子
.father{width:100px;height:100px;background-color: grey;display: flex;}
.child{width:50px;height:20px;background-color: red;margin: auto;}
.father{width:100px;height:100px;background-color: grey;display: flex;justify-content: center;align-items:center;}
.child{width:50px;height:20px;background-color: red;}
table-cell:使用了table-cell以及行內(nèi)塊元素來實現(xiàn)
.father{width:100px;height:100px;background-color: grey;display: table-cell;text-align:center;vertical-align: middle;}
.child{display:inline-block;width:50px;height:20px;background-color: red;}
屏幕上水平垂直居中
屏幕上水平垂直居中十分常用臼节,常規(guī)的登錄及注冊頁面都需要用到。要保證較好的兼容性珊皿,還需要用到表布局网缝。
.outer {
? ? display: table;
? ? position: absolute;
? ? height: 100%;
? ? width: 100%;
}
.middle {
? ? display: table-cell;
? ? vertical-align: middle;
}
.inner {
? ? margin-left: auto;
? ? margin-right: auto;
? ? width: 400px;
}