盒子水平居中是开发中很常见的需求,面试也经常会问到,下面我来总结一下水平居中的各种方法。
首先,先定义两个盒子box1和box2,为父子关系。
<style>
.box1{
background: lime;
margin: 100px auto;
width:300px;
height:300px
}
.box2{
background: #0074D9;
}
</style>
<div class="box1">
<div class="box2"></div>
</div>
一、已知盒子的宽高
1、absolute+负margin
<style>
.box1{
position: relative;
}
.box2{
width:100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
}
</style>
设置父盒子box1为绝对定位,子盒子box2为相对定位。box2在top和left方向上移动父盒子50%的距离
此时我们会发现盒子并没有水平垂直居中,因为盒子是以左上角为起点移动50%的,还要使用margin往回拉盒子50%的距离。
.box2{
width:100px;
height: 100px;
background: #0074D9;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px; /*宽度的一半*/
margin-top: -50px; /*高度的一半*/
}
再来看看,box2已经水平垂直居中了
2、absolute+margin
.box2{
width:100px;
height: 100px;
background: #0074D9;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin:auto
}
box2四个方向的偏移量都设为0,设置margin为auto会自动分配剩余空间。
二、未知盒子宽高
1、aboslute+transform
.box2{
background: #0074D9;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
使用css3新增的transform,不需要知道盒子的宽高,可以相对于自身的宽和高移动50%的距离,达到水平垂直居中。此方法存在兼容问题。
2、text-align+lineheight
.box1{
line-height: 300px;
text-align: center;
}
.box2{
display: inline-block; /*设为行内块元素*/
vertical-align: middle;
background: #0074D9;
}
子盒子box2先设置inline-block,父盒子设置text-align:center,达到水平居中,父盒子设置行高为自身高度,子盒子设置vertical-align:middle就可以达到垂直居中。
3、flex布局(推荐)
.box1{
display: flex; /*设置弹性盒子*/
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
}
设置父盒子为弹性盒子,并设置主轴和纵轴居中,即可达到效果。使用的最普遍,也最简单,作为css3属性也有兼容性的问题。关于flex布局请看阮一峰教程。http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
4、display:table-cell
.box1{
display: table-cell;
text-align: center;
vertical-align: middle
}
.box2{
display: inline-block;
}
设置父盒子为表格布局,子盒子设为行内块元素,就可以把子盒子当做表格元素使用,使用text-align和vertical-align属性就能做到垂直居中。