CSS 垂直水平居中方法(9 种)
1、flex
<div class="wrapper flex-center">
<p>hello world</p>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
//设置弹性子元素
.child{
margin:auto;
}
</style>
利用到了 2 个关键属性:justify-content
和 align-items
,都设置为 center
,即可实现居中。
需要注意的是,要把 flex-center
放在父级元素,
2、flex + margin
父级元素设置 flex,子元素设置 margin: auto;
。
<div class="wrapper">
<p>hello world</p>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid #ccc;
display: flex;
}
.wrapper > p {
margin: auto;
}
</style>
3、transform + absolute
一般用于图片的居中
<div class="wrapper">
<img src="1.png">
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid #ccc;
position: relative;
}
.wrapper > img {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
当然,也可以将父元素 wrapper 的相对定位,移入子元素 img 中,替换掉绝对定位。效果是一样的。
4、table-cell
利用 table 的单元格居中效果展示。与 flex 一样,需要写在父级元素上。
<div class="wrapper">
<p>hello world</p>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid;
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
5、absolute + 四个方向的值相等
使用绝对定位布局,设置 margin:auto;
,并设置 top、left、right、bottom 的 值相等即可
。
<div class="wrapper">
<p>hello world</p>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid;
position: relative;
}
.wrapper > p {
width: 170px;
height: 20px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
6、writing-mode
改变文字的显示方向
<div class="wrapper">
<div class="wrapper-inner">
<p>hello world</p>
</div>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid #ccc;
writing-mode: vertical-lr; /*使文字方向垂直*/
text-align: center;
}
.wrapper > .wrapper-inner {
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
width: 100%;
}
.wrapper > .wrapper-inner > p {
display: inline-block;
margin: auto;
text-align: left;
}
</style>
7、grid(网格布局)
<div class="wrapper">
<p>hello world</p>
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid;
display: grid;
}
.wrapper > p {
align-self: center;
justify-self: center;
}
</style>
8、::after
<div class="wrapper">
<img src="1.png">
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid;
text-align: center;
}
.wrapper::after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.wrapper > img {
vertical-align: middle;
}
</style>
9、::before
配合 font-size: 0;
使用;font-size: 0;
可以消除标签之间的间隙。
<div class="wrapper">
<img src="1.png">
</div>
<style>
.wrapper {
width: 300px;
height: 300px;
border: 1px solid;
text-align: center;
font-size: 0;
}
.wrapper::before {
display: inline-block;
vertical-align: middle;
font-size: 14px;
content: '';
height: 100%;
}
.wrapper > img {
vertical-align: middle;
font-size: 14px;
}
</style>