公司一个页面中的一个样式以下,使左边文字竖直排列且水平垂直居中:css
代码:html
<div class='left-tit'>已停止</div>
.left-tit{ width: 30px; height: 158px; border-radius: 5px 0 0 5px; text-align: center; font-size: 14px; color: #fff; letter-spacing: 4px; background: #eb5c5e; padding-top: 50px; padding-left: 5px; }
通常状况,我会用padding
(如上)或者用position+transform+margin
使文字竖直排放看起来居中,可是这样不够智能或显得比较冗余。性能
偶然发现,其实用line-height
就能不用具体控制padding数值,也不用多加代码而完美实现。
改善代码以下:spa
<div class='left-tit'> <span>已停止</span> </div>
.left-tit{ width: 30px; line-height: 158px; border-radius: 5px 0 0 5px; text-align: center; font-size: 14px; color: #fff; background: #eb5c5e; } .left-tit span{ line-height: 1.2; display: inline-block; vertical-align: middle; width: 14px; }
主要:设置外层line-height
及内部span
为inline-block
;两点结合真的是挺巧妙的,line-height
撑开盒子高度并保证文字垂直居中, inline-block
使得元素具备内联元素特性而水平居中,同时又具备块级元素的特性可以设置宽度。code