以下对div水平居中是基于这样的代码
<div class="box"></div>
第一种:div定宽+margin
.box {
height: 300px;
width: 300px;
margin: 0 auto;
background: #ccc;
}
第二种:div定宽+相对定位+margin负值(为width的一半)
.box {
position: relative;
height: 300px;
width: 300px;
left: 50%;
margin-left: -150px;
background: #ccc;
}
第三种:div不定宽+绝对定位+transform
<div class="box">hello world</div>
.box {
position: absolute;
transform: translateX(-50%);
left: 50%;
background: #ccc;
}