在日常开发中我们经常会遇到给一个盒子设置水平居中对齐的案例,那么接下来整理了几种比较常用的方法。
以下为盒子的嵌套关系
<body>
<div class="box">
<div></div>
</div>
</body>
子绝父相+magin
父元素相对定位,子元素绝对定位上下左右都设为0,给子盒子设置
magin:auto
.box {
position: relative;
margin: 50px auto;
width: 400px;
height: 400px;
border: 1px solid pink;
}
.box>div {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: skyblue;
}
子绝父相+margin
父元素相对定位,子元素绝对定位,上左各给父盒子的一半,然后通过
magin值再移动本身的一半。
.box {
position: relative;
margin: 50px auto;
width: 400px;
height: 400px;
border: 1px solid pink;
}
.box>div {
position: absolute;
top: 200px;
left: 200px;
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: skyblue;
}
绝对定位+transform
父元素相对定位,子元素绝对定位,上左各给50%,再通过
transform:translate向左、向上位移自身的一半。
.box {
position: relative;
margin: 50px auto;
width: 400px;
height: 400px;
border: 1px solid pink;
}
.box>div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: skyblue;
}
flex布局+主侧轴对齐方式
给父元素设置flex布局,通过
justify-content: center;和align-items: center;让弹性盒子(子盒子)主轴和侧轴方向对齐。
.box {
display: flex;
justify-content: center;
align-items: center;
margin: 50px auto;
width: 400px;
height: 400px;
border: 1px solid pink;
}
.box>div {
width: 200px;
height: 200px;
background-color: skyblue;
}
flex布局+margin
给父元素设置flex布局,再给弹性盒子(子盒子)设置
margin:auto;
.box {
display: flex;
margin: 50px auto;
width: 400px;
height: 400px;
border: 1px solid pink;
}
.box>div {
margin: auto;
width: 200px;
height: 200px;
background-color: skyblue;
}