實(shí)現(xiàn)CSS垂直居中的五大方法及優(yōu)缺點(diǎn)
你知道如何使CSS垂直居中嗎,這里和大家分享一下CSS垂直居中的幾種方法以及它們各自的優(yōu)缺點(diǎn),相信本文介紹一定會(huì)讓你有所收獲。
CSS垂直居中的幾種方法
利用CSS來實(shí)現(xiàn)對象的垂直居中有許多不同的方法,比較難的是選擇那個(gè)正確的方法。我下面說明一下我看到的好的方法和怎么來創(chuàng)建一個(gè)好的居中網(wǎng)站。
使用CSS實(shí)現(xiàn)垂直居中并不容易。有些方法在一些瀏覽器中無效。下面我們看一下使對象垂直集中的5種不同方法,以及它們各自的優(yōu)缺點(diǎn)。
CSS垂直居中方法一:
這個(gè)方法把一些div的顯示方式設(shè)置為表格,因此我們可以使用表格的vertical-alignproperty屬性。
- <dividdivid="wrapper">
- <dividdivid="cell">
- <divclassdivclass="content">
- Contentgoesherediv>
- div>
- div>
- #wrapper{display:table;}
- #cell{display:table-cell;vertical-align:middle;}
優(yōu)點(diǎn):
content可以動(dòng)態(tài)改變高度(不需在CSS中定義)。當(dāng)wrapper里沒有足夠空間時(shí),content不會(huì)被截?cái)?/p>
缺點(diǎn):
InternetExplorer(甚至IE8beta)中無效,許多嵌套標(biāo)簽(其實(shí)沒那么糟糕,另一個(gè)專題)
CSS垂直居中方法二:
這個(gè)方法使用絕對定位的div,把它的top設(shè)置為50%,topmargin設(shè)置為負(fù)的content高度。這意味著對象必須在CSS中指定固定的高度。
因?yàn)橛泄潭ǜ叨?,或許你想給content指定overflow:auto,這樣如果content太多的話,就會(huì)出現(xiàn)滾動(dòng)條,以免content溢出。
- <divclassdivclass="content">
- Contentgoesherediv>
- #content{
- position:absolute;
- top:50%;
- height:240px;
- margin-top:-120px;/*negativehalfoftheheight*/
- }
優(yōu)點(diǎn):
適用于所有瀏覽器
不需要嵌套標(biāo)簽
缺點(diǎn):
沒有足夠空間時(shí),content會(huì)消失(類似div在body內(nèi),當(dāng)用戶縮小瀏覽器窗口,滾動(dòng)條不出現(xiàn)的情況)#p#
CSS垂直居中方法三:
這種方法,在content元素外插入一個(gè)div。設(shè)置此divheight:50%;margin-bottom:-contentheight;。
content清除浮動(dòng),并顯示在中間。
- <dividdivid="floater">
- <dividdivid="content">
- Contentherediv>
- div>
- #floater{float:left;height:50%;margin-bottom:-120px;}
- #content{clear:both;height:240px;position:relative;}
優(yōu)點(diǎn):
適用于所有瀏覽器
沒有足夠空間時(shí)(例如:窗口縮小)content不會(huì)被截?cái)?,滾動(dòng)條出現(xiàn)
缺點(diǎn):
***我能想到的就是需要額外的空元素了(也沒那么糟,又是另外一個(gè)話題)
CSS垂直居中方法四:
這個(gè)方法使用了一個(gè)position:absolute,有固定寬度和高度的div。這個(gè)div被設(shè)置為top:0;bottom:0;。但是因?yàn)樗泄潭ǜ叨龋鋵?shí)并不能和上下都間距為0,因此margin:auto;會(huì)使它居中。使用margin:auto;使塊級元素垂直居中是很簡單的。
- <dividdivid="content">
- Contentherediv>
- #content{
- position:absolute;
- top:0;
- bottom:0;
- left:0;
- right:0;
- margin:auto;
- height:240px;
- width:70%;
- }
優(yōu)點(diǎn):簡單
缺點(diǎn):
IE(IE8beta)中無效
無足夠空間時(shí),content被截?cái)?,但是不?huì)有滾動(dòng)條出現(xiàn)。#p#
CSS垂直居中方法五:
這個(gè)方法只能將單行文本置中。只需要簡單地把 line-height 設(shè)置為那個(gè)對象的 height 值就可以使文本居中了。
- <div id="content">
- Content herediv>
- #content {height:100px; line-height:100px;}
優(yōu)點(diǎn):
適用于所有瀏覽器
無足夠空間時(shí)不會(huì)被截?cái)?/p>
缺點(diǎn):
只對文本有效(塊級元素?zé)o效)
多行時(shí),斷詞比較糟糕
這個(gè)方法在小元素上非常有用,例如使按鈕文本或者單行文本居中。
【編輯推薦】