在平时,我们经常会碰到让一个div框针对某个模块上下左右都居中(水平垂直居中),其实针对这种情况,我们有多种方法实现。
方法一
绝对定位方法:不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%)
; 当前div的父级添加相对定位 position: relative
;
1
div{
2
background:red;
3
position: absolute;
4
left:50%;
5
top:50%;
6
transform: translate(-50%, -50%);
7
}
方法二
绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值
1
div{
2
width:600px;
3
height: 600px;
4
background:red;
5
position: absolute;
6
left:50%;
7
top:50%;
8
margin-left:-300px;
9
margin-top:-300px;
10
}
方法三
绝对定位方法:绝对定位下 top
left
right
bottom
都设置0
1
div.child{
2
width: 600px;
3
height: 600px;
4
background: red;
5
position:absolute;
6
left:0;
7
top: 0;
8
bottom: 0;
9
right: 0;
10
margin: auto;
11
}
方法四
flex布局方法:当前div的父级添加flex css样式
1
.box{
2
height:800px;
3
display:flex;
4
align-items:center;
5
justify-content:center;
6
border:1px solid #ccc;
7
}
8
div.child{
9
width:600px;
10
height:600px;
11
background-color:red;
12
}
方法五
table-cell实现水平垂直居中: display: table-cell
vertical-align: middle
text-align: center
组合使用
1
.table-cell {
2
display: table-cell;
3
vertical-align: middle;
4
text-align: center;
5
width: 240px;
6
height: 180px;
7
border:1px solid #666;
8
}
方法六
绝对定位:calc() 函数动态计算实现水平垂直居中
1
.calc{
2
position: relative;
3
border: 1px solid #ccc;
4
width: 400px;
5
height: 160px;
6
}
7
.calc .child{
8
position: absolute;
9
width: 200px;
10
height: 50px;
11
left:-webkit-calc((400px - 200px)/2);
12
top:-webkit-calc((160px - 50px)/2);
13
left:-moz-calc((400px - 200px)/2);
14
top:-moz-calc((160px - 50px)/2);
15
left:calc((400px - 200px)/2);
16
top:calc((160px - 50px)/2);
17
}
以上方式均可实现垂直居中布局,个别方法有使用局限性,主流实现方式推荐 方法一
和 方法四
,即使用CSS3的平移样式或者Flex布局方式,其他方法虽然也能达到相同效果,但是兼容性和扩展性不是很好!