常用CSS居中方法集锦

总结

对于行内元素,可以使用center/margin:auto/text-align:center等实现水平居中。块级元素常用的居中方法有absolute,flex,padding,tabel-ceil,伪元素等技术实现。下文中各个方法实现效果为:

水平居中 垂直居中
行内元素 1,2,3,4 2,3,4
块级元素 1,2,3,5,6,7,8,9,10 2,3,5,6,7,8,9,10

1.水平居中,外层套上center标签,但是html5已经不支持该标签,使用margin:0 auto可以实现同样效果。

1
2
3
4
5
6
7
8
<div class="parent">
<center>
<div class="child1">
</div>
</center>
<div style="margin:0 auto;">
</div>
</div>

2.水平垂直居中,absolute+top/left/right/bottom,其中top/bottom/right/left的值相同则垂直水平居中,不同则相对中心位置偏移。

1
2
3
4
5
6
7
8
9
10
11
.parent{
position:relative;
}
.child{
position:absolute;
margin:auto;
top:0;
bottom:0;
right:0;
left:0;
}

3.absolute+transform,先利用left+top使child元素距离父组件左上角50%,再利用transform向左上偏移child元素宽高的一半,使child中心和parent中心重合。使用时需要注意兼容性。

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

4.文字居中:设置行高设置为元素高度,但是这种只能针对单行文字,若有换行样式会混乱。

1
2
3
<div style="width:800px;height:500px;background-color: #ff5f47;line-height: 500px;text-align: center;">
水平垂直居中
</div>

5.多行文字可以用tabel-cell实现。

1
2
3
4
5
6
7
8
9
10
11
12
.parent{
width:800px;
height:500px;
background-color: #ff5f47;
display: table-cell;
text-align:center;
vertical-align: middle;
}
.child{
background-color: green;
margin: auto
}

6.已知宽高,可利用padding+background-clip实现居中,设置padding为parent宽高减去child宽高的一半,同时设置background-clip:content-box。

1
2
3
4
5
6
7
8
9
10
11
12
.parent{
width:800px;
height:500px;
background-color: #ff5f47;
}
.child{
width:200px;
height: 100px;
background-color: green;
padding: 200px 300px;
background-clip:content-box;
}

7.flex布局实现居中,使用需要注意兼容性。

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent{
width:800px;
height:500px;
background-color: #ff5f47;
display: flex;
align-items: center;
justify-content: center;
}
.child{
width:200px;
height: 100px;
background-color: green;
}

8.display:table-cell实现居中,利用vertical-align让子元素垂直居中,再在子元素中利用margin:auto实现水平居中。

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent{
width:800px;
height:500px;
background-color: #ff5f47;
display: table-cell;
vertical-align: middle;
}
.child{
width:200px;
height: 100px;
background-color: green;
margin:auto;
}

9.伪元素实现居中,利用伪元素占位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.parent{
width:800px;
height:500px;
background-color: #ff5f47;
text-align: center;
}
.child{
width:200px;
height:100px;
background-color: green;
display: inline-block;
vertical-align: middle;
}
.parent::before{
content: '';
height: 100%;
display:inline-block;
vertical-align: middle;
}

10.使用calc计算padding的距离,如果只知道child的尺寸,可以通过padding: calc((100% - child_width)/2)实现居中。使用时需要注意兼容性。

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2021-2022 Yin Peng
  • 引擎: Hexo   |  主题:修改自 Ayer
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信