1 <title>第一种实现方式:定位 + 偏移(需要知道子元素的宽高)</title> 2 <style> 3 .father { 4 300px; 5 height: 300px; 6 background-color: deepskyblue; 7 margin: 100px auto; 8 position: relative; 9 } 10 .son { 11 100px; 12 height: 100px; 13 background-color: pink; 14 /*实现水平垂直居中*/ 15 position: absolute; 16 top: 50%; 17 left: 50%; 18 margin-top: -50px; 19 margin-left: -50px; 20 } 21 </style> 22 </head> 23 24 <body> 25 <div class="father"> 26 <div class="son"></div> 27 </div> 28 </body>
1 <title>第二种实现方式:定位 + transform(不需要知道子元素的宽高)</title> 2 <style> 3 .father { 4 300px; 5 height: 300px; 6 background-color: deepskyblue; 7 margin: 100px auto; 8 position: relative; 9 } 10 11 .son { 12 100px; 13 height: 100px; 14 background-color: pink; 15 /*实现水平垂直居中*/ 16 position: absolute; 17 top: 50%; 18 left: 50%; 19 transform: translate(-50%, -50%); 20 } 21 </style> 22 </head> 23 24 <body> 25 <div class="father"> 26 <div class="son"></div> 27 </div> 28 29 </body>
1 <title>第三种实现方式:让父盒子为flex容器Document</title> 2 <style> 3 .father { 4 300px; 5 height: 300px; 6 background-color: deepskyblue; 7 display: flex; 8 justify-content: center; 9 align-items: center; 10 } 11 12 .son { 13 100px; 14 height: 100px; 15 background-color: pink; 16 } 17 </style> 18 </head> 19 20 <body> 21 <div class="father"> 22 <div class="son"></div> 23 </div> 24 </body>
1 <title>第四种实现方式:margin:auto;实现绝对定位元素的水平方向居中</title> 2 <style> 3 .father { 4 300px; 5 height: 300px; 6 background-color: deepskyblue; 7 position: relative; 8 } 9 10 .son { 11 100px; 12 height: 100px; 13 background-color: pink; 14 /*实现水平垂直居中*/ 15 position: absolute; 16 top: 0; 17 left: 0; 18 bottom: 0; 19 right: 0; 20 margin: auto; 21 } 22 </style> 23 </head> 24 25 <body> 26 <div class="father"> 27 <div class="son"></div> 28 </div> 29 </body> 30 31 </html>