如何使div垂直水平居中

使 div 垂直水平居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<style>
.parent {
width: 600px;
height: 600px;
}
.child {
width: 200px;
height: 200px;
background-color: rebeccapurple;
}
</style>
...
<div class="parent">
<div class="child"></div>
</div>
...

方案一

1
2
3
4
5
6
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

方案二

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

方案三

1
2
3
4
5
6
7
.parent {
display: grid;
}
.child {
align-self: center;
justify-self: center;
}

方案四

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
text-align: center;
}
.parent::before {
content: '';
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%