前面已經談過垂直居中的做法,這一篇把它和兩種常見的水平居中方式組裝起來,形成可以直接套用的完整寫法。
<div style="float: left; width: 275px; height: 375px; border: solid red;">
<div style="height: 375px; width: 275px; position: relative;
display: table-cell; vertical-align: middle;">
<div style="position: static; position: absolute\9; top: 50%;">
<div style="position: relative; top: -50%; text-align: center;">
<div style="width: 275px;">
<div style="width: 160px; word-wrap: break-word;
table-layout: fixed; word-break: break-all; text-align: left;">
內容
</div>
</div>
</div>
</div>
</div>
</div>
結構是四層:最外層決定尺寸,第二层 display: table-cell 負責垂直居中,第三層用 top: 50% 下推,第四層用 top: -50% 回拉,最內層則用 text-align: center 處理文字水平居中。
那個 position: absolute\9 是 IE 專屬的 hack(反斜線加 9),目的是讓舊 IE 走定位路線而非 table-cell。它會讓驗證失敗,也讓程式碼變得難讀。
<div style="float: left; width: 275px; height: 375px; border: solid red;">
<div style="height: 375px; width: 275px; position: relative;
display: table-cell; vertical-align: middle;">
<div style="position: static; position: absolute\9; top: 50%;">
<div style="position: relative; top: -50%;">
<div style="margin: 0 auto; width: 160px;
word-wrap: break-word; table-layout: fixed; word-break: break-all;">
內容
</div>
</div>
</div>
</div>
</div>
與前者的唯一差別在最內層:把 text-align: center 換成 margin: 0 auto。text-align 讓文字在區塊內居中,margin: 0 auto 讓區塊本身在父容器中居中——這兩件事層次不同,選哪一個取決於你要居中的是文字還是多個區塊。使用 margin auto 的前提是該元素必須有明確寬度。
這兩個範例刻意加入了 word-wrap: break-word、table-layout: fixed 與 word-break: break-all,用來處理「英文長字串必須強制換行」的情境。在固定寬度的欄位中,一串沒有空白的長網址若無條件換行,就會撐破容器。實務上這三個屬性通常一起寫,作為長內容的保險。
這套四層嵌套是為了相容 IE6/7 而生的。若只需支援現代瀏覽器,同樣的效果是:
.box {
width: 275px;
height: 375px;
display: flex;
align-items: center;
justify-content: center;
}
.box .inner {
width: 160px;
overflow-wrap: break-word;
}
兩層取代四層,沒有 hack,也不需要計算 -50%。