CSS水平垂直居中
chenpeng 2020-04-30 CSS
# 1、利用定位和 transform 属性实现
<style>
.parent{
width: 500px;
height: 500px;
background-color: cornflowerblue;
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
IE9 以下不支持 transform
# 2、利用 flex 布局实现
<style>
.parent{
width: 500px;
height: 500px;
background-color: cornflowerblue;
display: flex;
justify-content: center;
align-items: center;
}
.child{
background-color: red;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
兼容性不好,很多浏览器都不支持
# 3、利用 table 布局实现
<style>
.parent{
width: 500px;
height: 500px;
background-color: cornflowerblue;
display: table;
}
.child{
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
IE8 以下不支持