CSS 文字垂直居中

原始 democss

htmlhtml

  <div class ="box">

    <div class="text">

      我是單行測試文字

    </div>

  </div>

  <div class="box">

    <div class="text">

       我是多行文字我是多行文字是多行文字我是多行文字我是多行文字我是多行文字我是多行文字我是多行文字我是多行文字我是多行文字我是>多行文字我是多行文字

    </div>

  </div>

css測試

  .box{ border:1px solid #f00; background-color:#eee; width:500px; height:100px;}

  .text{}

效果圖:spa

1、單行文字的垂直居中code

解決方案:line-height方法htm

cssblog

   .box{ border:1px solid #f00; background-color:#eee; width:500px; height:100px;line-height:100px;}

效果圖圖片

說明:能夠看到,這種方法會使得單行文字居中,而多行文字由於被設置了與容器等大的 line-height,致使文字溢出。因此該方法只適合單行文字的居中。get

 

2、多行文字的垂直居中it

解決方案:vertical-align 方法

css

  .box{ border:1px solid #f00; background-color:#eee; width:500px; height:100px;vertical-align:middle;display:table-cell;}
  .text{}

效果圖:

說明:能夠看到,這種方法可以使得單行文字、多行文字都居中。可是由於 table-cell 是 inline 類型,因此會致使原來的塊級元素每一個 div 一行移動到了同一行。若是須要分列兩行,須要在外面額外添加容器對位置進行控制。

 

 

相關閱讀:

大小不固定的圖片、多行文字的水平垂直居中

line-height、vertical-align與display:inline-block的一些問題  

相關文章
相關標籤/搜索