居中的多种实现
程序员文章站
2022-07-14 14:24:58
...
方法1
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
align-items: center;
justify-items: center;
}
p {
background: red;
}
方法2(掌握)
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
align-items: center;
justify-content: center;
}
p {
background: red;
}
方法3(掌握)
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: grid;
}
p {
background: red;
margin: auto;
}
方法4(掌握)
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
align-items: center;
justify-content: center;
}
p {
background: red;
}
方法5(掌握)
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
}
p {
background: red;
margin: auto;
}
方法6
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: table-cell;
vertical-align: middle;
text-align: center;
}
p {
background: red;
display: inline-block;
}
方法7(掌握)
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
position: relative;
}
p {
position: absolute;
left: 50%;
top: 50%;
transfrom: translate(-50%, -50%);
margin: 0;
}
方法8
<div class="box">
<p>hello</p>
</div>
.box {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
}
.box::after {
content: '';
line-height: 200px;
}
p {
display: inline-block;
}
方法9(废弃)
<div class="box">
<p>hello</p>
</div>
/* method 9*/
.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;
}
总结
• 推荐使用flex居中的方式
上一篇: 数据结构-栈和队列的多种实现方法