DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
DIV 水平與垂直居中方案(二):層的居中、長字換行與垂直滾動
編輯:CSS詳解     

這一組範例涵蓋四個實務上常遇到的細節問題:層本身的垂直居中、超長英文換行、以及區塊內的垂直捲動。

四、DIV 層垂直居中

<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 垂直滾動

<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,能保留空間但不顯示捲軸。

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