這一組範例涵蓋四個實務上常遇到的細節問題:層本身的垂直居中、超長英文換行、以及區塊內的垂直捲動。
<div style="width: 275px; height: 375px; border: solid red;">
<div style="background: green; height: 375px; width: 275px;
position: relative; display: table-cell; vertical-align: middle;">
<div style="background: red; position: static; position: absolute\9; top: 50%;">
<div style="background: blue; position: relative; top: -50%;">
內容
</div>
</div>
</div>
</div>
三層結構:外層定尺寸,中层用 table-cell 加 vertical-align 做居中,內層以 top: 50% 與 top: -50% 的組合完成微調。範例刻意替三層套上不同背景色,方便你看清各層的實際範圍——這在除錯時是很實用的技巧。
<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: 85px; word-wrap: break-word;
table-layout: fixed; word-break: break-all; margin: 0 auto;">
內容
</div>
</div>
</div>
</div>
</div>
重點在 85px 的窄欄加上換行控制。英文單字之間靠空白斷行,但超長字串(網址、亂碼、程式碼片段)沒有空白,瀏覽器預設不會切斷,就會溢出容器。word-break: break-all 允許在任意字元處斷行,word-wrap: break-word 作為後備,table-layout: fixed 則確保欄寬不被內容撐開。三者搭配是處理使用者生成內容時的標準保險。
<div style="width: 160px; height: 260px; overflow-y: scroll;
border: 1px solid;">
</div>
overflow-y: scroll 會永遠顯示垂直捲軸,即使內容不足。若希望只在內容溢出時才出現,改用 overflow-y: auto。這兩者的差別在視覺上很明顯:scroll 會恆常佔用幾像素寬度來放捲軸,auto 則不會。
實務建議:多數情況用 auto,版面較乾淨;只有在「捲軸出現與不出現會導致左右元素跳動」時,才用 scroll 固定佔位。現代的替代方案是 scrollbar-gutter: stable,能保留空間但不顯示捲軸。