布局-水平居中

结构:

1     <div class="parent">
2         <div class="child">DEMO</div>
3     </div>

样式:

1.方案1. text-align + inline-block  (对行内元素有效)

   .parent {
        background-color: grey;
         500px;


        text-align: center;
    }
    .child {
        display: inline-block;
        
        background-color: skyblue;
    }/*内容会继承父元素的居中,若不想,则单独再设置一下text-align:left*/

2.方案2.  table + margin

1 .child {
2         display: table;/*表现上像block元素,但table的宽度随内容*/
3         margin: 0 auto;
4 
5         background-color: skyblue;
6     }
7     /*优点:只设置child,不用关系parent的样式,IE8+支持display:table
8       缺点:不兼容IE678,将结构直接换成table*/

3.方案3.  absolute + transform

 1     .parent {
 2         position: relative;
 3     }
 4     .child {
 5         position: absolute;/*脱离文档流的*/
 6         left: 50%;/*相对于容器的百分比*/
 7         transform: translateX(-50%);/*相对于自身的百分比*/
 8 
 9         background-color: skyblue;
10     }
11     /*优点:居中元素不会对其他元素产生影响
12       缺点:不兼容IE678*/

4.方案4.  flex  +  justify-content

1 .parent {
2         display: flex;
3         justify-content: center;/*设置水平方向上flex-item的对齐方式*/
4     }
5     /*优点:只要设置.parent样式
6       缺点:不兼容IE678*/

或者:
.parent {
display:flex;
}
.child {
margin: 0 auto;
}
原文地址:https://www.cnblogs.com/Janejxt/p/5878831.html