在CSS中水平居中是非常简单的:
如果是一个行内元素,就再它的父元素添加text-align: center
,如果是一个块级元素自身添加margin: auto
属性。
但垂直居中是比较麻烦的,今天介绍几种垂直居中的方法。
1.单行文本垂直(line-height)
效果:
2.块级(包含行内块)元素垂直居中
早期的做法,它要求元素定宽和定高
<style>
.box2 {
width: 400px;
height: 200px;
border: 1px solid #ff0000;
position: relative
}
.box2>div {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /* -(height/2) */
margin-left: -50px; /* -(width/2) */
width: 100px;
height: 100px;
background: yellow;
}
</style>
<!--html代码-->
<div class="box2">
<div></div>
</div>
这个方法的本质是:看下图
3.position + transform实现垂直居中(不定高,不定宽)
<style>
.box3 {
width: 400px;
height: 200px;
border: 1px solid #ff0000;
position: relative
}
.box2>div {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
transform: translate(-50%, -50%);
background: yellow;
}
</style>
<!--html代码-->
<div class="box3">
<div></div>
</div>
4.使用table-cell(适合于文字)
<style>
.box {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background: purple;
}
.box span {
display: inline-block;
vertical-align: middle;
}
</style>
<div class="box">
<span>多行文字,此处居中设置</span>
</div>
此时span在容器box中处于居中
5.使用flex布局(不定高,不定宽)
<style>
.flex {
display: flex;
/* 垂直居中 */
align-items: center;
width: 300px;
height: 300px;
/* 水平居中 */
justify-content: center;
background: #ff0000;
}
</style>
<div class="flex">
<div class="flex-item">123</div>
</div>