附图:
1. 利用Flex布局实现
demo.html
<div class="demo demo-flex"><span>孤云将野鹤,岂向人间住。莫买沃洲山,时人已知处。</span></div>
style.css
.demo {
width: 120px;
height: 200px;
border: 1px solid red;
/*line-height: 25px;*/
font-size: 12px;
}
.demo-flex{
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
2. 利用属性 line-height
<div id="box">
<span>文本上下居中</span>
</div>
style.css
#box {
width: 200px;
height: 120px;
border: 1px solid red;
text-align: center;
}
#box span {
line-height: 120px;
}
注意: 这个方法只适用于 单行文本
3. 利用position 定位来实现
html
<div class="box">
<a class="remind">春宵一刻值千金,花有清香月有阴。歌管楼台声细细,秋千院落夜沉沉。</a>
</div>
css
.box{
width: 500px; height: 500px; border: 1px solid red; text-align: center;
} 定位方法 (一) .remind {
position: absolute;
top: %;
left: %;
transform: translate(-%, -%);
} 定位方法 (二) .remind {
position: absolute;
top: ;
left: ;
right: ;
bottom: ;
margin: auto ;
height: ;
}
4. 利用 vertical-align 来实现
即在父容器内放一个100%高度的伪元素,让文本和伪元素垂直对齐,从而达到垂直居中的目的。
<div id="box">
<span>两个黄鹂鸣翠柳</span>
</div>
css
#box {
width: 200px;
height: 120px;
border: 1px solid red;
text-align: center;
}
#box::before { // 伪元素
content: " ";
display: inline-block;
height: %;
width: %;
vertical-align: middle;
}
#box span {
vertical-align: middle;
}
5. 利用 Flex布局 来实现
<div id="box">
<span>两个黄鹂鸣翠柳</span>
</div>
css
#box {
width: 200px;
height: 120px;
border: 1px solid red;
/*text-align: center;*/
display: flex;
align-items: center;
justify-content: center;
}