一、定位+margin
- 使用子绝父相定位水平垂直各走 50%,这时盒子位于父盒子偏右下方的位置。
- 用 margin 让子盒子往左移动子盒子宽度的一半,往上移动子盒子高度的一半。
.father {
/* 父盒子相对定位 */
position: relative;
width: 600px;
height: 400px;
background-color: skyblue;
}
.son {
/* 子盒子绝对定位 */
position: absolute;
left: 50%;
top: 50%;
/* 往左移动子盒子宽度的一半 */
margin-left: -100px;
/* 往上移动子盒子高度的一半 */
margin-top: -50px;
width: 200px;
height: 100px;
background-color: pink;
}
二、定位+平面位移
使用平面位移和 定位+ margin 原理一样,在盒子子绝父相定位后往回移动自身的一半。
- 使用子绝父相定位水平垂直各走 50%,这时盒子位于父盒子偏右下方的位置。
- 给父盒子设置translate(-50%, -50%),向左移动子盒子宽度的一半,向上移动子盒子高度的一半。
这种写法的优点是不管父盒子和子盒子的宽度怎么改变,都不会影响子盒子垂直水平居中的效果。
.father {
/* 父盒子相对定位 */
position: relative;
width: 600px;
height: 400px;
background-color: skyblue;
}
.son {
/* 子盒子绝对定位 */
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
background-color: pink;
/* 自动往左移动子盒子宽度的一半,往上移动子盒子高度的一半 */
/* 它会随着子盒子宽高的变化而变化 */
transform: translate(-50%, -50%);
}
三、flex 弹性布局
弹性盒子居中的方法,只需要三行代码即可实现。
- 给父盒子设置 display: flex; 让父盒子变成弹性容器,里面子盒子会自动变为弹性盒子。
- 给父盒子设置主轴和侧轴的对齐方式为居中对齐。
<div class="father">
<div class="son"
</div>
.father {
/* 添加 flex 布局 */
display: flex;
/* 主轴居中对齐 */
justify-content: center;
/* 侧轴居中对齐 */
align-items: center;
width: 600px;
height: 400px;
background-color: skyblue;
}
.son {
width: 200px;
height: 100px;
background-color: pink;
}
四、利用 display:table-cell
把父盒子转化为单元格,子盒子转化为行内块元素,再给父盒子设置文字居中。
.father {
/* 转化为单元格 */
display: table-cell;
/* 文字居中对齐 */
text-align: center;
vertical-align: middle;
width: 600px;
height: 400px;
background-color: skyblue;
}
.son {
/* 转化为行内块元素 */
display: inline-block;
width: 200px;
height: 100px;
background-color: pink;
}
五、定位 + margin: auto方法
利用了 margin: 0 auto; 的原理,设置四个方向的定位都为 0,是为了让盒子在四个边界里去 auto。
.father {
/* 父盒子相对定位 */
position: relative;
width: 600px;
height: 400px;
background-color: skyblue;
}
.son {
/* 子盒子绝对定位 */
position: absolute;
/* 设置四个方向的定位都为 0 */
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 100px;
background-color: pink;
}
六、计算父盒子和子盒子之间的距离
- 给子盒子设置上外边距为 (父盒子的高度-子盒子的高度)/2
- 给子盒子设置左外边距为 (父盒子的宽度-子盒子的宽度)/2
很麻烦,不实用。这个方法必须给父盒子添加边框才有效果。
.father {
width: 600px;
height: 400px;
background-color: skyblue;
border: 1px solid #000;
}
.son {
width: 200px;
height: 100px;
background-color: pink;
/* (父盒子的高度-子盒子的高度)/2 */
margin-top: 150px;
/* (父盒子的宽度-子盒子的宽度)/2 */
margin-left: 200px;
}