2013/01/05

水平與垂直置中 第二頁

單行文字的置中。以下方法都不使用 TABLE 元素,而是要在 DIV 元素 置中。單行文字的置中,其水平置中可用 text-align:center。垂直置中可以將 line-height 宣告與 height 相同,此法只能用在單行文字的情形。

  • 風格用法:

    <style type='text/css'>
    .out1   {width:160px;
             border:solid 1px red;
             height:100px;
            }
    </style>
    <div class=out1 style='text-align:center'>
    <span>水平置中</span>
    </div>

    <div class=out1 style='line-height:100px'>
    <span>垂直置中</span>
    </div>

    <div class=out1 style='text-align:center; line-height:100px'>
    <span>中央</span>
    </div>

  • 執行結果:

    水平置中
    垂直置中
    中央

區塊元素的置中。先要將子區塊元素設為 display:inline-block。水平置中可用 text-align:center。垂直置中可以將父元素 line-height 宣告與 height 相同,然後子區塊必須設成 vertical-align:middle;line-height:1em。為了在 IE6 達成垂直置中,還必須加上 margin:expression();此法使用 parentNode, clientHeight 與數學函式 floor() 計算 margin。expression() 這行在個人電腦測試正常,可是移到部落格之後,會導致 IE6 停頓,所以用註解取消其功能;使用時請多測試。

  • 風格用法:

    <style type='text/css'>
    .blk   {width:200px;
            height:120px;
            border:solid 1px red;
            line-height:120px;
            text-align:center;
           }
    .blk DIV {width:100px;
              background:blue;
              display:inline-block; 
              vertical-align:middle;
              line-height:1em;
              /* margin:expression(Math.floor( (this.parentNode.clientHeight-this.clientHeight)/2 )+'px auto');  */ 
             }
    </style>
    <div class=blk>
    <div>中央<br />中央</div>
    </div>

  • 執行結果:

    中央
    中央
水平與垂直置中(你正在看 第二頁) : 第一頁 第二頁 第三頁 第四頁