置中看似簡單,真要同時做到上下左右都居中,反而常讓人卡住。以下示範兩種可靠寫法。
div {
position: fixed;
margin: auto;
left: 0; right: 0;
top: 0; bottom: 0;
width: 200px;
height: 150px;
}
原理是把四邊都拉到 0,再讓 margin: auto 自動分配剩餘空間。前提是元素必須有明確的寬高,否則 auto 無從計算。
只需要單一軸向置中時,把另一軸的其中一邊拿掉即可:想水平居中就刪掉 top:0 或 bottom:0;想垂直居中就刪掉 left:0 或 right:0。
先把元素左上角挪到視窗中心,再用負的 margin 把自己拉回一半尺寸:
.dialog {
position: fixed;
_position: absolute; /* IE6 hack */
z-index: 1;
top: 50%;
left: 50%;
margin: -141px 0 0 -201px;
width: 400px;
height: 280px;
border: 1px solid #CCC;
line-height: 280px;
text-align: center;
font-size: 14px;
background-color: #F4F4F4;
overflow: hidden;
}
這裡的 -141px 與 -201px 就是元素高度與寬度的一半(含 border)取負值。缺點很明顯:尺寸寫死了,日後改寬高就得重算一次。
能自由用 fixed 的場合就用寫法一,它自適應、免計算。若必須支援老 IE,再用寫法二並搭配 _position hack。今天更現代的作法是 display: flex 加上 justify-content 與 align-items,三行就能搞定,且完全不必理會元素尺寸。