CSS让物体居中
在网页中经常会用到物体居中显示,如果是文本或inline元素使用text-align:center,但如果是上下左右都居中就需要借助定位布局来实现。
html代码如下:
<div class="container">
<div class="content"></div>
</div>
1
2
3
2
3
# 方法一:使用margin: auto
.content {
position: absolute;
width: 60%;
height: 40%;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: blue;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 方法二: top和left分别为50%,在给div一个基于自身50%的top、left偏移
.content {
position: absolute;
width: 60%;
height: 40%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: blue;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 方法三:使用flex布局,让子元素居中
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2025/09/05, 8:09:00