div固定寬高,水平垂直居中,根據所用單位不同,分成兩種情況,分別是“px”和“%”情況。
例:將三層div做出三個邊框,要求水平垂直居中。效果如圖
- 情況一(單位是px時):
只需要用絕對定位到屏幕中間,然后利用margin-left和margin-top取值就可以實現。
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結構不變。
<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>