【CSS】CSS实现垂直水平居中

已知父盒子宽度高度为200px,小盒子宽度高度为200px。

Posted by ARTROY on 2018-06-15

公共代码

HTML:

1
2
3
<section class="layout">
<div class="content"></div>
</section>

CSS:

1
2
3
4
5
6
7
8
9
10
.layout {
width: 200px;
height: 200px;
border: 1px solid #000;
}
.content {
width: 100px;
height: 100px;
border: 1px solid #f44;
}

方案一:absolute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
.layout {
position: relative;
}
/* 方法一 */
.content {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform:translate(-50%,-50%);
}
/* 方法二 */
.content{
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
}
/* 方法三 */
.content {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
/* 方法四 */
.content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
/*
* top、bottom、left和right 均设置为0
* margin设置为auto
*/
}

方案二:flex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* 公共设置 */
.layout {
display: flex;
}
/* 方法一: 父元素设置 */
.layout {
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
/* 方法二: 父元素设置 */
.layout {
justify-content: center;
place-items: center;
}
/* 方法三: 父元素+子元素 */
.layout {
display: flex;
justify-content: center; /* 水平居中 */
}
.content {
align-self: center;
}
/* 方法四: 子元素设置 */
.content {
margin: auto;
}
/* 方法五: 子元素设置 */
.content {
margin: 0 auto;
align-self: center;
}

方案三:grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 方法一 */
.layout {
display: grid;
justify-items: center;
align-items: center;
}
/* 方法二 */
.layout {
display: grid;
}
.content {
justify-self: center;
align-self: center;
}

方案四:table-cell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* 方法一 */
.layout {
display: table-cell; /* 设置样式 */
vertical-align: middle; /* 设置垂直居中 */
}
.content {
margin: 0 auto; /* 水平居中 */
display: inline-block;
}
/* 方法二 */
.layout {
display: table-cell; /* 设置样式 */
vertical-align: middle; /* 设置垂直居中 */
text-align: center;
}
.content {
display: inline-block;
}

方案五:伪元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.layout {
font-size: 0;
text-align: center;
}
.layout::before {
content: "";
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}
.content{
display: inline-block;
vertical-align: middle;
}


支付宝打赏 微信打赏

欣赏此文,打赏一下



-->