1. div絕對定位水平垂直居中【margin:auto實現絕對定位元素的居中】css
兼容性:,IE7及以前版本不支持web
div{ width: 200px; height: 200px; background: green; position:absolute; left:0; top: 0; bottom: 0; right: 0; margin: auto; }
2. div絕對定位水平垂直居中【margin 負間距】 這或許是當前最流行的使用方法。flex
div{ width:200px; height: 200px; background:green; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; }
3. div絕對定位水平垂直居中【Transforms 變形】spa
兼容性:IE8不支持code
div{ width: 200px; height: 200px; background: green; position:absolute; left:50%; /* 定位父級的50% */ top:50%; transform: translate(-50%,-50%); /*本身的50% */ }
4. 彈性盒模型-css不定寬高水平垂直居中orm
.box{ height:600px;/去掉高度,只能垂直居中。 display:flex; justify-content:center; align-items:center; /* aa只要三句話就能夠實現不定寬高水平垂直居中。 */ } .box>div{ background: green; width: 200px; height: 200px; }
5. 將父盒子設置爲table-cell元素,可使用text-align:center和vertical-align:middle實現水平、垂直居中。比較完美的解決方案是利用三層結構模擬父子結構blog
<p class="outerBox tableCell"> </p><p class="ok"> </p><p class="innerBox">tableCell</p> <p></p> <p></p> /* table-cell實現居中 將父盒子設置爲table-cell元素,設置 text-align:center,vertical-align: middle; 子盒子設置爲inline-block元素 */ .tableCell{ display: table; } .tableCell .ok{ display: table-cell; text-align: center; vertical-align: middle; } .tableCell .innerBox{ display: inline-block; }
6. 對子盒子實現絕對定位,利用calc計算位置it
<p class="outerBox calc"> </p><p class="innerBox">calc</p> <p></p> /*絕對定位,clac計算位置*/ .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); }
#div1 { position: absolute; left: 50px; width: calc(100% - 100px); border: 1px solid black; background-color: yellow; padding: 5px; text-align: center; }