demo.htmlcss
1 <div class="demo demo-flex"><span>孤雲將野鶴,豈向人間住。莫買沃洲山,時人已知處。</span></div>
style.csshtml
1 .demo { 2 width: 120px; 3 height: 200px; 4 border: 1px solid red; 5 /*line-height: 25px;*/ 6 font-size: 12px; 7 } 8 .demo-flex{ 9 display: flex; 10 align-items: center; 11 justify-content: center; 12 flex-direction: column; 13 }
<div id="box">
<span>文本上下居中</span>
</div>佈局
style.cssflex
1 #box { 2 width: 200px; 3 height: 120px; 4 border: 1px solid red; 5 text-align: center; 6 } 7 #box span { 8 line-height: 120px; 9 }
注意: 這個方法只適用於 單行文本spa
htmlcode
1 <div class="box"> 2 <a class="remind">春宵一刻值千金,花有清香月有陰。歌管樓臺聲細細,鞦韆院落夜沉沉。</a> 4 </div>
cssorm
1 .box{ 2 width: 500px; 3 4 height: 500px; 5 6 border: 1px solid red; 7 8 text-align: center; 9 } 10 11 定位方法 (一) 12 13 .remind { 14 position: absolute; 15 top: 50%; 16 left: 50%; 17 transform: translate(-50%, -50%); 18 } 19 20 定位方法 (二) 21 22 .remind { 23 position: absolute; 24 top: 0; 25 left: 0; 26 right: 0; 27 bottom: 0; 28 margin: auto 0; 29 height: 0; 30 }
即在父容器內放一個100%高度的僞元素,讓文本和僞元素垂直對齊,從而達到垂直居中的目的。htm
1 <div id="box"> 2 <span>兩個黃鸝鳴翠柳</span> 3 </div>
cssblog
1 #box { 2 width: 200px; 3 height: 120px; 4 border: 1px solid red; 5 text-align: center; 6 7 } 8 #box::before { // 僞元素 9 content: " "; 10 display: inline-block; 11 height: 100%; 12 width: 1%; 13 vertical-align: middle; 14 } 15 #box span { 16 vertical-align: middle; 17 }
1 <div id="box"> 2 <span>兩個黃鸝鳴翠柳</span> 3 </div>
cssrem
1 #box { 2 width: 200px; 3 height: 120px; 4 border: 1px solid red; 5 /*text-align: center;*/ 6 display: flex; 7 align-items: center; 8 justify-content: center; 9 }