div固定寬高,水平垂直居中,根據所用單位不一樣,分紅兩種狀況,分別是「px」和「%」狀況。css
例:將三層div作出三個邊框,要求水平垂直居中。效果如圖flex
只須要用絕對定位到屏幕中間,而後利用margin-left和margin-top取值就能夠實現。spa
1 <style type="text/css"> 2 3 .a { 4 border: 1px solid #00caca; 5 width: 900px; 6 height: 500px; 7 position: absolute; 8 top: 50%; 9 left: 50%; 10 margin-left: -450px; 11 margin-top: -250px; 12 13 display: flex; //flex讓內部div水平垂直居中 14 flex-direction: row; 15 justify-content: center; 16 align-items: center; 17 } 18 .b { 19 border: 1px solid #00cacc; 20 width: 80%; 21 height: 70%; 22 display: flex; 23 flex-direction: row; 24 justify-content: center; 25 align-items: center; 26 } 27 .c { 28 border: 1px solid #00fffb; 29 width: 60%; 30 height: 60%; 31 }
<body> <div class="a"> <div class="b"> <div class="c">ssssss</div> </div> </div> </body>
因爲%是基於父元素寬高,採用margin-left值爲負自己寬高一半失效,所以,須要計算定位top 和 left值,使其居中。代碼以下,其中,HTML結構不變。code
<style type="text/css"> body { width: 100%; //須要給body設置寬高 height: 100%; } .a { border: 1px solid #00caca; width: 80%; height: 80%; position: absolute; top: 10%; //根據自身寬高佔body的80%,推算定位top值 left: 10%; //同上 margin-left: 0; margin-top: 0; display: flex; flex-direction: row; justify-content: center; align-items: center; } .b { border: 1px solid #00cacc; width: 80%; height: 70%; display: flex; flex-direction: row; justify-content: center; align-items: center; } .c { border: 1px solid #00fffb; width: 60%; height: 60%; } </style>