CSS 实现盒子水平垂直居中的方法

效果展示

原始效果

居中效果

原始代码

html 部分

1
2
3
<div class="father">
<div class="son"></div>
</div>

css 部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
body {
background-color: #6ed0ff;
}

.father {
width: 300px;
height: 300px;
margin: 100px auto;
border-radius: 20px;
background-color: #be33ec;
box-shadow: 0 0 15px rgb(0, 0, 0);
}

.son {
width: 100px;
height: 100px;
border-radius: 20px;
background-color: #fcff00;
box-shadow: 0 0 10px rgb(0, 0, 0);
}

实现方法

absolute + margin

1
2
3
4
5
6
7
8
9
10
11
12
.father {
position: relative;
}

.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}

absolute + 负 margin

1
2
3
4
5
6
7
8
9
10
11
.father {
position: relative;
}

.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}

absolute + transform

1
2
3
4
5
6
7
8
9
10
.father {
position: relative;
}

.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

margin + transform

1
2
3
4
5
6
7
8
.father {
overflow: hidden;
}

.son {
margin: 50% auto;
transform: translateY(-50%);
}

flex

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

或者

1
2
3
4
5
6
7
.father {
display: flex;
}

.son {
   margin: auto;
}

grid

1
2
3
4
.father {
display: grid;
   place-items: center;
}

或者

1
2
3
4
5
6
7
8
.father {
display: grid;
}

.son {
align-self: center;
justify-self: center;
}

table-cell

1
2
3
4
5
6
7
8
9
.father {
display: table-cell;
text-align: center;
vertical-align: middle;
}

.son {
display: inline-block;
}

CSS 实现盒子水平垂直居中的方法
https://blog.xukaiyyds.cn/posts/ca5259af/
作者
xukaiyyds
发布于
2023年4月6日
更新于
2024年3月16日
许可协议