水平居中

------------恢复内容开始------------

html水平居中

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8     <style>
 9         .box1{
10             width: 500px;
11             height: 500px;
12             background-color: aqua;
13             /* position: relative; */
14         }
15         .box2{
16             width: 100px;
17             height: 100px;
18             background-color: orange;
19             position: absolute;
20            /* 水平居中 */
21             /* margin-left: auto;
22             margin-right: auto;
23            right: 0;
24             left: 0; */
25            
26             /* 垂直居中 */
27             /* margin-top: auto;
28             margin-bottom: auto;
29             top: 0;
30             bottom: 0; */
31             /* 位于父元素正中心 */
32             right: 0;
33             left: 0;
34             top: 0;
35             bottom: 0;
36             margin: auto;
37         }
38         /* 
39         水平布局
40           left+margin-left+border-left+padding-left+width+padding-right+border-right+margin-right+right=包含块的内容区的宽度
41 
42           -当我们开启绝对定位以后:
43           水平方向的布局等式就需要添加left和right两个值
44              此时 规则和之前一样 只是多添加了两个值:
45              当发生过度约束时,
46                如果9个值中没有 auto 则自动调整right以使我们的等式满足
47                如果auto,则自动调整auto的值以使等式成立
48 
49             -可设置为auto的值
50               margin width right left
51               
52               -因为 left和right 的默认值是auto,所以如果不设置left和right
53               则等式不满足时,会自动调整这两个值
54         
55 
56               垂直方向布局的等式也必须要满足:
57               top+margin-top/bottom+padding-top/bottom+border-top/bottom+height = 包含块的高度
58 
59         
60         */
61     </style>
62 </head>
63 <body>
64     <div class="box1">
65         <div class="box2"></div>
66     </div>
67 </body>
68 </html>
对于相对于谁居中就设置对应的包含块 position:relative;
即可对应居中
            position: absolute;
20            /* 水平居中 */
21             /* margin-left: auto;
22             margin-right: auto;
23            right: 0;
24             left: 0; */
25            
26             /* 垂直居中 */
27             /* margin-top: auto;
28             margin-bottom: auto;
29             top: 0;
30             bottom: 0; */
31             /* 位于父元素正中心 */
32             right: 0;
33             left: 0;
34             top: 0;
35             bottom: 0;
36             margin: auto;
 



------------恢复内容结束------------

原文地址:https://www.cnblogs.com/yqPhare/p/15394611.html