欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

CSS實(shí)現(xiàn)垂直居中的幾種方法

  發(fā)布時間:2011-09-05 22:43:52   作者:佚名   我要評論
最近上網(wǎng)上找了些關(guān)于CSS實(shí)現(xiàn)垂直居中的方法,方法挺多,下面就我看到的幾種好方法在這里說明一下,使用 CSS 實(shí)現(xiàn)垂直居中并不容易。
有些方法在一些瀏覽器中無效,因此,到底選擇哪種方法好,還要看具體情況。

方法一:
這個方法把一些 div 的顯示方式設(shè)置為表格,因此我們可以使用表格的 vertical-align property 屬性。

復(fù)制代碼
代碼如下:

<div id="wrapper">
<div id="cell">
<div class="content">
Content goes here</div>
</div>
</div>
#wrapper {display:table;}
#cell {display:table-cell; vertical-align:middle;}

優(yōu)點(diǎn):content 可以動態(tài)改變高度(不需在 CSS 中定義)。當(dāng) wrapper 里沒有足夠空間時, content 不會被截?cái)啵?
缺點(diǎn):Internet Explorer(甚至 IE8 beta)中無效,許多嵌套標(biāo)簽。

方法二:
這個方法使用絕對定位的 div,把它的 top 設(shè)置為 50%,top margin 設(shè)置為負(fù)的 content 高度。這意味著對象必須在 CSS 中指定固定的高度。
因?yàn)橛泄潭ǜ叨龋蛟S你想給 content 指定 overflow:auto,這樣如果 content 太多的話,就會出現(xiàn)滾動條,以免content 溢出。

復(fù)制代碼
代碼如下:

<div class="content">
Content goes here
</div>
#content {
  position:absolute;
  top:50%;
   height:240px;
   margin-top:-120px; /* negative half of the height */
}

優(yōu)點(diǎn):適用于所有瀏覽器,不需要嵌套標(biāo)簽
缺點(diǎn):沒有足夠空間時,content 會消失(類似div 在 body 內(nèi),當(dāng)用戶縮小瀏覽器窗口,滾動條不出現(xiàn)的情況)
方法三:
這種方法,在 content 元素外插入一個 div。設(shè)置此 div height:50%; margin-bottom:-contentheight;。
content 清除浮動,并顯示在中間。

復(fù)制代碼
代碼如下:

<div id="floater">
  <div id="content">
     Content here
  </div>
</div>
#floater {float:left; height:50%; margin-bottom:-120px;}
#content {clear:both; height:240px; position:relative;}

優(yōu)點(diǎn):適用于所有瀏覽器,沒有足夠空間時(例如:窗口縮小) content 不會被截?cái)?,滾動條出現(xiàn)
缺點(diǎn):唯一我能想到的就是需要額外的空元素了

方法四:
這個方法使用了一個 position:absolute,有固定寬度和高度的 div。這個 div 被設(shè)置為 top:0; bottom:0;。但是因?yàn)樗泄潭ǜ叨?,其?shí)并不能和上下都間距為 0,因此 margin:auto; 會使它居中。使用 margin:auto;使塊級元素垂直居中是很簡單的。

復(fù)制代碼
代碼如下:

<div id="content">
  Content here
</div>
#content {
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  margin:auto;
   height:240px;
   width:70%;
}

優(yōu)點(diǎn):簡單;
缺點(diǎn):IE(IE8 beta)中無效,無足夠空間時,content 被截?cái)?,但是不會有滾動條出現(xiàn);

方法五:
這個方法只能將單行文本置中。只需要簡單地把 line-height 設(shè)置為那個對象的 height 值就可以使文本居中了。

復(fù)制代碼
代碼如下:

<div id="content"> Content here</div>
#content {height:100px; line-height:100px;}

優(yōu)點(diǎn):適用于所有瀏覽器,無足夠空間時不會被截?cái)?
缺點(diǎn):只對文本有效(塊級元素?zé)o效),多行時,斷詞比較糟糕
這個方法在小元素上非常有用,例如使按鈕文本或者單行文本居中。

相關(guān)文章

最新評論