盒子居中看似簡單,卻有許多不同的實作方式,各有適用場景。以下整理了八種常見做法,並附上程式碼示範。HTML 結構皆採用同一份:
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
純粹靠寬高與 margin 拼湊而成,不太靈活。
#container { width:600px; height:500px; border:1px solid #000; margin:auto; }
#box { width:200px; height:200px; margin:150px 200px; background-color:#0ff; }
利用負的 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; }
非常常用的一種方法,透過四邊歸零搭配 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; }
利用 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; }
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; }
靈活運用 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;
}
不需要知道寬高,較為靈活。只要讓左右百分比相同即可水平居中,上下百分比相同即可垂直居中。
#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; }
以 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; }
以上八種方法各有千秋,可依專案需求與相容性考量靈活選用。