DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> 關於CSS
CSS 垂直居中與水平居中方法大總結
編輯:關於CSS     

居中是 CSS 排版中的常見需求,以下整理了單行、層級、文字等多種居中情境的實用寫法。

1. 單行垂直居中

文字要在層中垂直居中,vertical-align 屬性是做不到的。這裡有個巧妙做法:讓 height 的高度與 line-height 相同。<div style="line-height:500px;height:500px;"></div>

2. 層水平居中

設 div 寬度小於父 div,再設 margin:0 auto; 即可讓 div 居中:#childdiv {width:200px; margin:0 auto;}

3. 層中文字水平居中

在 childdiv 加上 text-align:center; 即可。

4. div 層垂直居中

用 display:table-cell 搭配 vertical-align:middle,再透過絕對定位微調:<div style="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></div></div></div>

5. 垂直水平居中,英文超長換行

在方法四的基礎上,外層加上 float:left,內層加上 word-break:break-all 等斷行屬性,即可讓超長英文在居中時自動換行。

6. div 垂直捲動

加上 overflow-y:scroll 就能讓內容過多時出現垂直捲軸:<div style="width:160px; height:260px; overflow-y:scroll; border:1px solid;">內容</div>

7. 垂直居中搭配 text-align 水平居中

在垂直居中的結構中,最內層加上 text-align:center 或 text-align:left 配合固定寬度,就能靈活控制文字的水平對齊方式。

8. 垂直居中搭配 margin 水平居中

在垂直居中的最內層用 margin:0 auto; 搭配固定寬度,同樣能實現水平居中,適合需要斷行的長文本場景。

以上八種寫法涵蓋了單行文字、div 層級與長文本等常見居中需求,可依實際情境靈活選用。

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