四种方式
第一种:采用绝对定位,使用 margin-top 和 margin-left(已知盒子宽高)
第二种:采用绝对定位,使用 transform 平移方式
第三种:采用绝对定位,上下左右为0,margin: auto
第四种:采用 flex 布局,设置 justify-content: center 和 align-items: center
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| <!DOCTYPE html> <html lang="zh_CN">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>盒子水平垂直居中</title> <style> .box1 { position: relative; width: 200px; height: 200px; margin-bottom: 20px; background-color: pink; }
.box2 { position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; background-color: blue; }
.box3 { position: relative; width: 200px; height: 200px; margin-bottom: 20px; background-color: pink; }
.box4 { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background-color: blue; }
.box5 { position: relative; width: 200px; height: 200px; margin-bottom: 20px; background-color: pink; }
.box6 { position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100px; height: 100px; margin: auto; background-color: blue; }
.box7 { display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; background-color: pink; }
.box8 { width: 100px; height: 100px; background-color: blue; } </style> </head>
<body> <div class="box1"> <div class="box2"></div> </div>
<div class="box3"> <div class="box4"></div> </div>
<div class="box5"> <div class="box6"></div> </div>
<div class="box7"> <div class="box8"></div> </div> </body>
</html>
|