水平垂直居中的几种方式
Chao 工程师

公共代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* 公共代码 */
<style>
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
}

.box {
background: green;
}

.box.size{
width: 100px;
height: 100px;
}
</style>

<div class="wp">
<div class="box size">123123</div>
</div>
/* 公共代码 */

1.absolute + 负margin

适用于盒子定宽的情况

1
2
3
4
5
6
7
8
9
10
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}

2.absolute + margin auto

适用于盒子定宽的情况

这种方式通过设置各个方向的距离都是0,此时再将margin设为auto,就可以在各个方向上居中了

1
2
3
4
5
6
7
8
9
10
11
.wp {
position: relative;
}
.box {
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

3.absolute + calc

适用于盒子定宽的情况

1
2
3
4
5
6
7
8
.wp {
position: relative;
}
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
}

4.absolute + transform

1
2
3
4
5
6
7
8
9
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

5.line-height

利用行内元素居中属性也可以做到水平垂直居中

把box设置为行内块元素,通过text-align就可以做到水平居中,vertical-align也可以在垂直方向做到居中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.wp {
line-height: 300px;
/* 水平居中 */
text-align: center;
font-size: 0px;
}
.box {
/* 修正文字 */
font-size: 16px;
line-height: initial;
text-align: left;

display: inline-block;
/* 在父元素中居中 */
vertical-align: middle;
}

6.css-table

1
2
3
4
5
6
7
8
.wp {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}

7.flex布局

1
2
3
4
5
.wp {
display: flex;
justify-content: center;
align-items: center;
}

8.grid

1
2
3
4
5
6
7
.wp {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}
 Comments