方法一:
div絕對定位水平垂直居中【margin: auto實現絕對定位元素的居中】,兼容性:IE7及之前版本不支持
div{ width: 200px; height: 200px; background: green; position:absolute; left:0; top: 0; bottom: 0; right: 0; margin: auto; } |
方法二:div絕對定位水平垂直居中【margin負間距】
div{ width:200px; height: 200px; background:green; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; } |
方法三:div絕對定位水平垂直居中【Transform變形】,兼容性:IE8不支持
div{ width: 200px; height: 200px; background: green; position:absolute; left:50%; /* 定位父級的50% */ top:50%; transform: translate(-50%,-50%); /*自己的50% */ } |
方法四:CSS不定寬高水平垂直居中
.box{ height:600px; display:flex; justify-content:center;/*水平居中*/ align-items:center;/*垂直居中*/ /* 只要三句話就可以實現不定寬高水平垂直居中。 */ } .box>div{ background: green; width: 200px; height: 200px; } |
方法五:將父級設置爲table-cell元素,可以使用text-aligin:center和vertical-align:middle實現水平垂直居中,比較完美的方法是利用三層結構模擬父子結構
.tableCell{ width: 100px; height: 100px; display: table; } .tableCell .ok{ display: table-cell; text-align: center; vertical-align: middle; background-color: yellow; } .tableCell .innerBox{ display: inline-block; background-color: green; } <div class="outerBox tableCell"> <div class="ok"> <div class="innerBox">tableCell</div> </div> <div> |
方法六:對盒子實現絕對定位,利用calc計算位置
.calc{ position: relative; width: 500px; height: 120px; background-color: yellow; } .calc .innerBox{ width: 200px; height: 50px; 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); background-color: green; } <div class="outerBox calc"> <div class="innerBox"></div> <div> |