css實現行內文字垂直居中

 

以前本人一直使用浮動、相對定位、絕對定位和display:table等css的方法進行定位。網上得知flex可實現彈性佈局,符合將來發展趨勢,隨嘗試。css

1:讓盒子行內文字垂直居中,解決思路是講文字的行高設置爲盒子的高度。佈局

p {
           border:#333333 solid 1px;
           height:50px;
           line-height:50px;
           margin-bottom:30px;
        }

 

 

2:讓盒子行內文字垂直居中,解決思路是對盒子的高度設定,而後對盒子的padding-top和padding-bottom設置相同的值。flex

 p {
           border:#333333 solid 1px;
           padding-top:30px;
           padding-bottom:30px;
           margin-bottom:30px;
        }

3:讓盒子行內文字垂直居中,解決思路是讓盒子的display屬性變成table,而後文字添加span標籤,span屬性display:table-cellspa

p {
           border:#333333 solid 1px;
           height:60px;
           display:table;
           width:100%;
           margin-bottom:30px;
        }
        p span {
            display:table-cell;
            vertical-align:middle;
        }
<p><span>中華人民共和國</span></p>

4:讓盒子行內文字垂直居中,解決思路是讓盒子display的屬性變成flexcode

        p {
           border:#333333 solid 1px;
           height:60px;
           display:flex;
           align-items:center;
           margin-bottom:30px;
        }
<p><span>中華人民共和國</span></p>

若是讓「中華人民共和國」水平也居中的話,css調整爲:blog

p {
           border:#333333 solid 1px;
           height:60px;
           display:flex;
           align-items:center;/*垂直方向*/
           justify-content:center;/*水平方向*/
           margin-bottom:30px;
        }
相關文章
相關標籤/搜索