在css中的单行文本垂直居中一般常见设置height和line-height相同即可。但是如果多行,文本就会溢出。
特意总结了多行文本垂直居中的办法
- 使用table-cell
<style>
.single{
height: 80px;
border: 1px solid red;
display: table-cell;
width: 200px;
vertical-align: middle;
}
</style>
<div class="single">
table-cell&vertical-align方式实现
</div>
- 父元素设置
line-height
,子元素设置vertical-align
<style>
.single2{
width: 200px;
height: 200px;
border: 1px solid red;
line-height: 200px;
}
.single2 span{
display: inline-block;
line-height: 20px;
vertical-align: middle;
}
</style>
<div class="single2">
<span>line-height&vertical-align方式实现</span>
</div>
- 定位+CSS3
<style>
.single3{
height: 200px;
line-height: 200px;
position: relative;
border: 1px solid red;
}
.single3 span{
position: absolute;
top: 50%;
transform: translateY(-50%);
line-height: 20px;
}
</style>
<div class="single3">
<span>定位&动画实现(测试文字测试文字测试文字测试文字测试文字)</span>
</div>
- table-cell
<style>
li{
list-style: none;
display: flex;
height: 80px;
}
.left{
width: 30%;
float: left;
display: table;
height: 100%;
}
.left>div{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.right{
width: 70%;
float: left;
border: 1px solid #ccc;
background: rgba(0,0,0,0.8);
box-sizing: border-box;
margin-right: 30px;
}
</style>
<ul>
<li>
<div class="left">
<div>黄焖鸡米饭</div>
</div>
<div class="right"></div>
</li>
<li>
<div class="left">
<div>鸡公煲</div>
</div>
<div class="right"></div>
</li>
<li>
<div class="left">
<div>黄焖鸡米饭(超级辣)</div>
</div>
<div class="right"></div>
</li>
</ul>