方案一
div絕對定位水平垂直居中【margin:auto實(shí)現(xiàn)絕對定位元素的居中】
div{
? ? ? ? ? ? width: 200px;
? ? ? ? ? ? height: 200px;
? ? ? ? ? ? background: green;
? ? ? ? ? ? position:absolute;
? ? ? ? ? ? left:0;
? ? ? ? ? ? top: 0;
? ? ? ? ? ? bottom: 0;
? ? ? ? ? ? right: 0;
? ? ? ? ? ? margin: auto;
? ? ? ? }
方案二
div絕對定位水平垂直居中【margin 負(fù)間距】? ? 這或許是當(dāng)前最流行的使用方法咆瘟。
div{
? ? ? ? ? ? width:200px;
? ? ? ? ? ? height: 200px;
? ? ? ? ? ? background:green;
? ? ? ? ? ? position: absolute;
? ? ? ? ? ? left:50%;
? ? ? ? ? ? top:50%;
? ? ? ? ? ? margin-left:-100px;
? ? ? ? ? ? margin-top:-100px;
? ? ? ? }
方案三
div絕對定位水平垂直居中【Transforms 位移】
div{
? ? ? ? ? ? width: 200px;
? ? ? ? ? ? height: 200px;
? ? ? ? ? ? background: green;
? ? ? ? ? ? position:absolute;
? ? ? ? ? ? left:50%;? ? /* 定位父級(jí)的50% */
? ? ? ? ? ? top:50%;
? ? ? ? ? ? transform: translate(-50%,-50%); /*自己的50% */
? ? ? ? }
方案四
flex彈性布局居中
.box{
? ? ? ? ? ? height:600px;
? ? ? ? ? ? display: -webkit-flex;
? ? ? ? ? ? display: flex;
? ? ? ? ? ? justify-content:center;
? ? ? ? ? ? align-items:center;
? ? ? ? ? ? ? /* 只要三句話就可以實(shí)現(xiàn)不定寬高水平垂直居中烛愧。 */
? ? ? ? }
方案五
將父盒子設(shè)置為table-cell元素鬼雀,可以使用text-align:center和vertical-align:middle實(shí)現(xiàn)水平、垂直居中抓韩。比較完美的解決方案是利用三層結(jié)構(gòu)模擬父子結(jié)構(gòu)
? ? ? ? .one {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 100px;
height: 100px;
background-color: red;
}
.two {
vertical-align: middle;
display: inline-block;
}
方案六
對子盒子實(shí)現(xiàn)絕對定位,利用calc計(jì)算位置
/*絕對定位,clac計(jì)算位置*/
.calc{
? position: relative;
}
.calc? .innerBox{
? position: absolute;
? left: -webkit-calc((500px - 200px)/2);
? top: -webkit-calc((120px - 50px)/2);
? left: -moz-calc((500px - 200px)/2);
? top: -moz-calc((120px - 50px)/2);
? left: calc((500px - 200px)/2);
? top: calc((120px - 50px)/2);