DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
CSS 布局中的居中問題:水平與垂直一次講透
編輯:布局實例     

居中是 CSS 布局中最常被問到的需求之一,無論是整個 DIV、圖片還是文字,都有對應的做法。本文逐一破解。

如何讓 DIV 水平居中

body { text-align: center; }
#center { margin-right: auto; margin-left: auto; }

父層設 text-align:center 讓內容居中,IE 這樣就足夠;但在 Firefox 中還需在子元素加上 margin-right:auto; margin-left:auto; 才能生效。若想讓整個頁面居中,建議拆成多個 div,各自定義左右 auto 邊距即可。

如何讓圖片在 DIV 中垂直居中

用背景的方式最簡單:

body { background: url(logo.gif) #FFF no-repeat center; }

關鍵是最後的 center,它定義圖片位置;也可寫成 top left、bottom right 或直接給數值。

如何讓文字在 DIV 中垂直居中

文字無法用背景法,可用「增加行高」的變通做法:

#center{
  margin-right:auto; margin-left:auto;
  height:200px; width:400px;
  background:#F00;
  vertical-align:middle;
  line-height:200px;
}

把行高 line-height 設得與整個 DIV 同高,再插入文字,就能讓文字垂直居中。

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