div水平垂直居中顯示

經過今天一翻改進,終於找出瞭解決DIV垂直居中的辦法。就跟隨本站小編一起去了解下吧,想了解更多相關信息請持續關注我們應屆畢業生考試網!

div水平垂直居中顯示

  一:表格佈局法

這個方法把一些 div 的顯示方式設置爲表格,因此我們可以使用表格的 vertical-align 屬性。

Content goes here

#wrapper { display: table; } #cell { display: table-cell; vertical-align: middle; }

優點:

content 可以動態改變高度(不需在 CSS 中定義)。當 wrapper 裏沒有足夠空間時, content 不會被截斷

缺點:

Internet Explorer(甚至 IE8 beta)中無效,許多嵌套標籤(其實沒那麼糟糕,另一個專題)

  二:假借圖片法

這個方法把一些 div 的顯示方式設置爲inline-block,和圖片一樣,因此我們可以使用圖片的 vertical-align 屬性。

Content goes here

#wrapper { display: table; } #likeImg { display: inline-block; vertical-align: center; }

優點:

在各種瀏覽器中兼容性都非常好,ie6和7中有間距問題

缺點:

很容易影響其他的佈局,導致網頁佈局全部癱瘓

  方法三:絕對定位法

這個方法使用絕對定位的 div,把它的' top 設置爲 50%,top margin 設置爲負的 content 高度。這意味着對象必須在 CSS 中指定固定的高度。

因爲有固定高度,或許你想給 content 指定 overflow:auto,這樣如果 content 太多的話,就會出現滾動條,以免content 溢出。

Content goes here

#content { position: absolute; top: 50%; height: 240px; margin-top: -120px; /* 盒子本身高度的一半 */ }

優點:

適用於所有瀏覽器

不需要嵌套標籤

缺點:

沒有足夠空間時,content 會消失(類似div 在 body 內,當用戶縮小瀏覽器窗口,滾動條不出現的情況)

  方法四

這種方法,在 content 元素外插入一個 div。設置此 div height:50%; margin-bottom:-contentheight;

content 清除浮動,並顯示在中間。

Content here

#floater { float: left; height: 50%; margin-bottom: -120px; } #content { clear: both; height: 240px; position: relative; }

優點:

適用於所有瀏覽器

沒有足夠空間時(例如:窗口縮小) content 不會被截斷,滾動條出現

缺點:

唯一我能想到的就是需要額外的空元素了,可能對於某些強迫症患者來說是不願意的(這個方法的應用應該也很廣)

  方法五

這個方法使用了一個 position:absolute,有固定寬度和高度的 div。這個 div 被設置爲 top:0; bottom:0;。但是因爲它有固定高度,其實並不能和上下都間距爲 0,因此 margin:auto; 會使它居中。使用 margin:auto;使塊級元素垂直居中是很簡單的。

Content here

#content { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; height: 240px; width: 70%; }

優點:

簡單粗暴,代碼簡單,其實設計者當初也根本沒想到也能這樣用,但是聰明的大家硬是鑿出了一條簡單的路。

缺點:

IE(IE8 beta)中無效

無足夠空間時,content 被截斷,但是不會有滾動條出現