子盒子在父盒子中居中大约有九种方法,九种方法又可分门别类的分为五种类型:
- 利用定位,即给父盒子设置相对定位,给子盒子设置绝对定位(3种)
- 利用弹性布局,即给父盒子设置display: flex;(3种)
- 给父盒子设置display: table-cell;(1种)
- 给子盒子设置一个同级span标签(1种)
- 强行用text-align:center;vertical-align:middle;设置成居中布局(1种)
1.利用定位,即给父盒子设置相对定位,给子盒子设置绝对定位
/* 第一种 */
.father {
position: relative
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
/* 第二种 */
.father {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
/* 第三种 */
.father {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
2.利用弹性布局,即给父盒子设置display: flex;
/* 第四种 */
.father {
display: flex;
}
.child {
margin: auto;
}
/* 第五种 */
.father {
display: flex;
align-items: center;
justify-content: center;
}
.child {
}
/* 第六种 */
.father {
display: flex;
justify-content: center;
}
.child {
align-self: center;
}
3. 给父盒子设置display: table-cell;
/* 第七种 */
.father {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
4. 给子盒子设置一个同级span标签
/* 第八种 */
.father {
text-align:center;
}
.child {
vertical-align: middle;
display: inline-block;
}
span.child1 {
width: 0;
height: 100%; /* 有所限制,父盒子的高度必须已知 */
vertical-align: middle;
display: inline-block;
}
5. 强行用text-align:center;vertical-align:middle;设置成居中布局
/* 第九种 */
.father {
text-align: center;
line-height: 666px; /* 有所限制,父盒子的高度必须已知 */
}
.child {
vertical-align: middle;
display: inline-block
}
6.总结
总的来说,这几种方法都有其可取之处,小编最推荐的还是前两种类型共六种方法,即利用定位或弹性布局,因为不涉及父盒子的宽高是否固定,那这样我们在设置居中的时候就少了一些限制。
但在实际操作过程中,还是要看自己的标签结构来确定,但大部分情况都可以用定位或弹性布局来解决。