<div class="box">
<p>hello</p>
</div>
要使<p>hello</p>垂直水平居中, 你知道多少种方式呢?
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;
}
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;
}
display:grid+margin: auto;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
}
p {
background: red;
margin: auto;
}
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;
}
display:flex+margin: auto;
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
}
p {
background: red;
margin: auto;
}
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;
}
- 绝对定位 +
transfrom
.box {
width: 200px;
height: 200px;
border: 1px solid;
position: relative;
}
p {
position: absolute;
left: 50%;
top: 50%;
transfrom: translate(-50%, -50%);
margin: 0;
}
::after设置line-height
.box {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
}
.box::after {
content: '';
line-height: 200px;
}
p {
display: inline-block;
}
- 不推荐
.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;
}