【Web】CSS实现绝对定位元素水平垂直居中

  网页中常常需用让绝对定位元素水平垂直居中,下面介绍2种方法:

一 元素宽度未知

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <style>
 6         .father {
 7             width: 800px;
 8             height: 400px;
 9             background-color: pink;
10             margin: 100px auto;
11             position: relative;
12         }
13         .son {
14             width: 10%;
15             height: 100px;
16             background-color: purple;
17 
18             height: 50%;  
19             overflow: auto;  
20             margin: auto;  
21             position: absolute;  
22             top: 0; left: 0; bottom: 0; right: 0;
23         }
24     </style>
25     <title>Document</title>
26 </head>
27 <body>
28     <!-- 绝对定位 水平垂直居中 -->
29      <div class="father">
30         <div class="son"></div>
31      </div>
32 </body>
33 </html>
34 </html>

二 元素宽度已知

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <style>
 6         .father {
 7             width: 800px;
 8             height: 400px;
 9             background-color: pink;
10             margin: 100px auto;
11             position: relative;
12         }
13         .son {
14             width: 200px;
15             height: 100px;
16             background-color: purple;
17             position: absolute;
18             left: 50%;
19             margin-left: -100px;
20 
21             top: 50%;
22             margin-top: -50px;
23         }
24     </style>
25     <title>Document</title>
26 </head>
27 <body>
28     <!-- 绝对定位 水平垂直居中 -->
29      <div class="father">
30         <div class="son"></div>
31      </div>
32 </body>
33 </html>

二 元素宽度已知

  使用CSS3中的新特性transform变形来做,移动盒子的位置

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <style>
 6         .father {
 7             width: 800px;
 8             height: 400px;
 9             background-color: pink;
10             margin: 100px auto;
11             position: relative;
12         }
13         .son {
14              width: 20%;/*相对于父级的百分比*/
15              height: 30%;
16              background-color: purple;
17              position: absolute;
18              top: 50%;
19              left: 50%;
20              transform: translate(-50%, -50%);/*相对于自己的百分比*/
21         }
22     </style>
23     <title>Document</title>
24 </head>
25 <body>
26     <!-- 绝对定位 水平垂直居中 -->
27      <div class="father">
28         <div class="son"></div>
29      </div>
30 </body>
31 </html>
32 </html>
原文地址:https://www.cnblogs.com/h--d/p/7596609.html