DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
Web 開發中讓盒子水平垂直居中的多種方法
編輯:前端技巧     

盒子居中看似簡單,卻有許多不同的實作方式,各有適用場景。以下整理了八種常見做法,並附上程式碼示範。HTML 結構皆採用同一份:

<body>
    <div id="container">
        <div id="box"></div>
    </div>
</body>

1.0 固定寬高 + margin 居中

純粹靠寬高與 margin 拼湊而成,不太靈活。

#container { width:600px; height:500px; border:1px solid #000; margin:auto; }
#box { width:200px; height:200px; margin:150px 200px; background-color:#0ff; }

2.0 負 margin 居中

利用負的 margin 達到居中,但必須事先知道固定寬高,限制較大。

#container { position:relative; width:600px; height:500px; border:1px solid #000; margin:auto; }
#box { position:absolute; width:200px; height:200px; left:50%; top:50%; margin:-100px -100px; background-color:#0ff; }

3.0 絕對定位居中

非常常用的一種方法,透過四邊歸零搭配 margin auto。

#container { position:relative; width:600px; height:500px; border:1px solid #000; margin:auto; }
#box { position:absolute; width:200px; height:200px; left:0; top:0; right:0; bottom:0; margin:auto; background-color:#0ff; }

4.0 table-cell 居中

利用 table-cell 控制垂直居中。

#container { display:table-cell; width:600px; height:500px; vertical-align:middle; border:1px solid #000; }
#box { width:200px; height:200px; margin:0 auto; background-color:#0ff; }

5.0 flex 居中

CSS3 引入的新布局方式,相當好用,缺點是 IE9 及以下不相容。

#container {
    display:-webkit-flex; display:flex;
    -webkit-align-items:center; align-items:center;
    -webkit-justify-content:center; justify-content:center;
    width:600px; height:500px; border:1px solid #000; margin:auto;
}
#box { width:200px; height:200px; background-color:#0ff; }

6.0 transform 居中

靈活運用 transform 屬性,較為新穎,缺點是 IE9 不相容。

#container { position:relative; width:600px; height:600px; border:1px solid #000; margin:auto; }
#box {
    position:relative; top:50%; left:50%; width:200px; height:200px;
    transform:translate(-50%, -50%);
    -webkit-transform:translate(-50%, -50%);
    -ms-transform:translate(-50%, -50%);
    -moz-transform:translate(-50%, -50%);
    background-color:#0ff;
}

7.0 寬高不確定時的絕對定位百分比

不需要知道寬高,較為靈活。只要讓左右百分比相同即可水平居中,上下百分比相同即可垂直居中。

#container { position:relative; width:600px; height:500px; border:1px solid #000; margin:auto; }
#box { position:absolute; left:30%; right:30%; top:25%; bottom:25%; background-color:#0ff; }

8.0 利用 button 居中

以 button 作為外層容器,內部的區塊元素會自動垂直居中,只需再處理水平居中即可。

<button>
    <div></div>
</button>
button { width:600px; height:500px; border:1px solid #000; }
div { width:200px; height:200px; margin:0 auto; background-color:#0ff; }

以上八種方法各有千秋,可依專案需求與相容性考量靈活選用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved