1、flex
<div class="wrapper flex-center">
<p>horizontal and vertical</p>
</div>
`
```css
.wrapper {
border: 1px solid
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
2、transform + absolute
<div class="wrapper">
<p>居中</p>
</div>
.wrapper {
border: 1px solid #ccc;
position: relative;
}
.wrapper p {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
absolute + 四个方向的值相等
使用绝对定位布局,设置 margin:auto;,并设置 top、left、right、bottom 的 值相等即可
<div class="wrapper">
<p>horizontal and vertical</p>
</div>
.wrapper {
border: 1px solid #ccc;
position: relative;
}
.wrapper p {
width: 170px;
height: 20px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}