其他平台文章地址
- github:
- csdn:
前端页面的居中是平常开发中比较常见的布局,以下将从水平居中、垂直居中、水平垂直居中三个角度分析不同的布局方法。
水平居中
法一:行内元素水平居中
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container {
text-align: center;
width: 100%;
height: 400px;
background: #ccc;
}
.container .box {
width: 100px;
height: 100px;
background: yellow;
display: inline-block;
}
示意图:
法二:margin实现水平居中
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container {
width: 100%;
height: 400px;
background: #ccc;
}
.container .box {
width: 100px;
height: 100px;
background: yellow;
margin: 0 auto;
}
示意图:
法三:flex弹性布局(可实现多个块级元素水平居中)
html:
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
css:
.container {
width: 100%;
height: 400px;
background: #ccc;
display: flex;
justify-content: center;
}
.container .box {
width: 100px;
height: 100px;
background: yellow;
margin-left: 10px;
}
.container .box:first-child {
margin-left: 0;
}
示意图:
注意:flex布局会将margin包含在内,并且上面的场景通过text-align: center;同样可以做到,也就是方法一。
垂直居中
法一:行内元素垂直居中
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container {
width: 100%;
height: 400px;
line-height: 400px;
background: #ccc;
}
.container .box {
width: 100px;
height: 100px;
background: yellow;
display: inline-block;
vertical-align: middle;
}
演示图: