盒子水平和垂直居中
垂直居中的常用三种方法
定义容器
<div class="box1">
<div class="box2"></div>
</div>
- 先让子盒子的上边缘与父盒子的水平位置重叠,再将子盒子往上移动自身的一半
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 150px; /* 子盒子上边距移动到父盒子的中心位置*/
margin-top: -51px; /* 子盒子往上移动自身盒子的一半,自身高度+边框 */
}
- 使用表格的vertical-align:middle实现盒子的垂直居中
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
display: table-cell; /* 以表格形式展现内容 */
vertical-align: middle;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
}
- 使用margin计算盒子的上下边距实现垂直居中
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
margin-top: 99px; /* (父盒子的高度-子盒子的高度) / 2 */
}
实现效果
水平居中的常用方法四种方法
定义容器
<div class="box1">
<div class="box2"></div>
</div>
- 使用margin: 0 auto
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
margin: 0 auto;
}
- 使用margin左右边距
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
margin-left: 99px; /* (父盒子的宽度-子盒子的宽度) / 2 */
}
- 先让子盒子左边缘与父盒子中心点重叠,再把子盒子往左移自身一半的宽度
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
left: 150px; /* 子盒子左边距移动到父盒子的中心位置*/
margin-left: -51px; /* 子盒子往左移动自身盒子的一半,自身宽度+边框 */
}
- 把盒子转换成行内块,然后使用text-align属性使盒子水平居中
.box1 {
width: 300px;
height: 300px;
border: 1px solid blue;
text-align: center;
}
.box2 {
width: 100px;
height: 100px;
border: 1px solid red;
display: inline-block; /* 设置子盒子为行内块 */
}
实现效果