div 水平垂直居中的方法

在平时,我们经常会碰到让一个 div 框针对某个模块上下左右都居中(水平垂直居中),其实针对这种情况,我们有多种方法实现。

transform

绝对定位方法:不确定当前 div 的宽度和高度,采用 transform: translate(-50%,-50%); 当前 div 的父级添加相对定位(position: relative;)

图片展示:

image-20200418180158961

代码如下:

1
2
3
4
5
6
7
div{
background:red;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);
}

margin

绝对定位方法:确定了当前 div 的宽度,margin 值为当前 div 宽度一半的负值

图片展示: 如方法一的图片展示

代码如下:

1
2
3
4
5
6
7
8
9
10
div{
width:600px;
height: 600px;
background:red;
position: absolute;
left:50%;
top:50%;
margin-left:-300px;
margin-top:-300px;
}

使用top left right bottom

绝对定位方法:绝对定位下 top left right bottom 都设置 0

图片展示: 如方法一的图片展示

代码如下:

1
2
3
4
5
6
7
8
9
10
11
div.child{
width: 600px;
height: 600px;
background: red;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}

flex 布局

flex 布局方法:当前 div 的父级添加 flex css 样式

展示图如下:

image-20200418180312674

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.box{
height:800px;
-webkit-display:flex;
display:flex;
-webkit-align-items:center;
align-items:center;
-webkit-justify-content:center;
justify-content:center;
border:1px solid #ccc;
}
div.child{
width:600px;
height:600px;
background-color:red;
}

table-cell

table-cell 实现水平垂直居中: table-cell middle center 组合使用

展示图如下:

image-20200418180340408

代码如下:

1
2
3
4
5
6
7
8
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border:1px solid #666;
}

calc() 函数

绝对定位:calc() 函数动态计算实现水平垂直居中

展示图如下:

image-20200418180354103

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.calc{
position: relative;
border: 1px solid #ccc;
width: 400px;
height: 160px;
}
.calc .child{
position: absolute;
width: 200px;
height: 50px;
left:-webkit-calc((400px - 200px)/2);
top:-webkit-calc((160px - 50px)/2);
left:-moz-calc((400px - 200px)/2);
top:-moz-calc((160px - 50px)/2);
left:calc((400px - 200px)/2);
top:calc((160px - 50px)/2);
}