css水平垂直居中的几种方式

112 阅读1分钟
<div class="box">   
    <p>hello</p>  
</div>

要使<p>hello</p>垂直水平居中, 你知道多少种方式呢?

  1. grid布局 align-items: center; + justify-items: center;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
align-items: center;
justify-items: center;
}
p {
background: red;
}
  1. grid布局 align-items: center; + justify-content: center;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
align-items: center;
justify-content: center;
}
p {
background: red;
}
  1. display:grid + margin: auto;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
}
p {
background: red;
margin: auto;
}
  1. flex布局 align-items: center; + justify-content: center;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
align-items: center;
justify-content: center;
}
p {
background: red;
}
  1. display:flex + margin: auto;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
}
p {
background: red;
margin: auto;
}
  1. display: table-cell;+ vertical-align: middle;+ text-align: center; + display: inline-block;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: table-cell;
vertical-align: middle;
text-align: center;
}
p {
background: red;
display: inline-block;
}

display: table; + display: table-cell; + vertical-align: middle; + text-align: center;

.box {
width: 200px;
height: 200px;
border: 1px solid;
display: table;
}
p {
background: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
  1. 绝对定位 + transfrom
.box {
width: 200px;
height: 200px;
border: 1px solid;
position: relative;
}
p {
position: absolute;
left: 50%;
top: 50%;
transfrom: translate(-50%, -50%);
margin: 0;
}
  1. ::after设置line-height
.box {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
}
.box::after {
content: '';
line-height: 200px;
}
p {
display: inline-block;
}
  1. 不推荐
.box {
width: 200px;
height: 200px;
border: 1px solid;
position: relative;
}
p {
background: red;
/*必须要设置宽高*/
width: 100px;
height: 40px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}