CSS垂直居中网页布局实现的5种方法.docx
《CSS垂直居中网页布局实现的5种方法.docx》由会员分享,可在线阅读,更多相关《CSS垂直居中网页布局实现的5种方法.docx(27页珍藏版)》请在冰豆网上搜索。
CSS垂直居中网页布局实现的5种方法
ThereareafewdifferentwaystoverticallycentreobjectswithCSS,butitcanbedifficulttochoosetherightone.I’llshowyouallthebestwaysI’veseenandalsohowtocreateanicelittlecenteredwebsite.
VerticalcenteringwithCSSisn’taneasythingtodo.Therearemanydifferentwaysthatmaynotworkinsomebrowsers.Let’sreview5differentwaystoverticallycenteringobjects,aswellastheprosandconsofeachmethod.(Youcanseemytestpagebrieflyexplainingallofthem.)
Method1
Thismethodsetssome
Contentgoeshere
#wrapper{display:
table;}
#cell{display:
table-cell;vertical-align:
middle;}
TheGoods
∙Thecontentcandynamicallychangeheight(doesn’thavetobedefinedinCSS)
∙Contentdoesn’tgetcutoffwhenthereisn’tenoughroominthewrapper
TheBads
∙Doesn’tworkinInternetExplorer(noteventheIE8beta)
∙Lotsofnestedtags(notreallythatbad,thisisasubjectivetopic)
Method2
Thismethodwilluseanabsolutelypositioneddiv,whichhasthetopsetto50%andthetopmarginsettonegativehalftheheightofthecontent.Thismeanstheobjectmusthaveafixedheight,thatisdefinedbyCSS.
Becauseithasafixedheight,youmaywanttosetoverflow:
auto;tothecontentdiv,soifthereistoomuchcontenttofitin,ascrollbarwillappear,insteadofthecontentcontinuingonoutsidethediv!
<divid="content">
ContentHere
</div>
#content{position:
absolute;top:
50%;height:
240px;margin-top:
-120px;/*negativehalfoftheheight*/}
∙Worksinallbrowsers
∙Doesn’trequirenestedtags
∙Whenthereisn’tenoughspace,thecontentdisappears(suchaswhenthedivisinsidethebodyandtheusershrinksthebrowserwindow,ascrollbarwillnotappear)
Method3
Inthismethod,wewillinsertadivabovethecontentelement.Thiswillbesettoheight:
50%;andmargin-bottom:
-contentheight;.Thecontentwillthenclearthefloatandendupinthemiddle.
Contenthere
#floater{float:
left;height:
50%;margin-bottom:
-120px;}
#content{clear:
both;height:
240px;position:
relative;}
∙Whenthereisn’tenoughspace(ie.thewindowshrinks)ourcontentwillnotbecutoff,andascrollbarwillappear.
∙OnlyoneIcanthinkofisthatitrequiresanextraemptyelement(whichisn’tthatbad,anothersubjectivetopic)
Method4
Thismethodusesaposition:
absolute;divwithafixedwidthandheight.Thedivisthentoldtostretchtotop:
0;bottom:
0;.Itcan’tbecauseofthefixedheight,somargin:
auto;willmakeitsitinthemiddle.Thisissimilartousingtheverycommonmargin:
0auto;tohorizontallycentreblockelements.
0;left:
0;right:
0;
margin:
auto;height:
240px;width:
70%;}
∙Easy
∙Doesn’tworkinInternetExplorer(doesworkinIE8Beta)
∙Contentiscutoffwithoutscrollbarifthereisn’tenoughroominthecontainer
Method5
Thismethodwillonlycentreasinglelineoftext.Simplysettheline-heighttotheheightoftheobject,andthetextsitsinthemiddle
#content{height:
100px;line-height:
100px;}
∙Doesn’tgetcutoffwhentheisn’tenoughspace
∙Onlyworksontext(noblockelements)
∙Whenthereismorethanasingleline(likewhenitwraps),itbreaksbadly
Thismethodisveryusefulonsmallelements,suchastocentrethetextinsideabuttonorsingle-linetextfield.
WhichMethod?
Myfavouritemethodisnumber3—usingafloaterandclearingthecontent.Itdoesn’thaveanymajordownsides.Becausethecontentwillclear:
both;,youcanalsoputotherelementsaboveit,andwhenthewindowscollapses,thecenteredcontentwillnotcoverthemup.Seethedemo.
#top{float:
right;width:
100%;text-align:
center;}
Nowyouknowhowitworks,let’sstartcreatingasimplebutinterestingwebsite!
Thefinalproductwilllooksomethinglikethis:
Step1
It’salwaysgoodtostartwithsemanticmarkup.Thisishowourpagewillbestructured:
∙#floater(topushthecontentintothemiddle)
∙#centred(thecentrebox)
o#side
▪#logo
▪#nav(unorderedlist
o#content
∙#bottom(forcopyright,etc.)
HereisthexhtmlcodeIwillbeusing:
DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http:
//www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
//www.w3.org/1999/xhtml">
ACompany
Holisticlyre-engineervalue-addedoutsourcingafterprocess-centriccollaborationandidea-sharing.
Energisticallysimplifyimpactfulnichemarketsviaenabledimperatives.
Holisticlypredominatepremiuminnovationaftercompellingscenarios.
Seamlesslyrecaptiualizehighstandardsinhumancapitalwithleading-edgemanufacturedproducts.
Distinctivelysyndicatestandardscompliantschemasbeforerobustvortals.
Uniquelyrecaptiualizeleveragedweb-readinessvis-a-visout-of-the-boxinformation.
Efficientlyembracecustomizedweb-readinessratherthancustomerdirectedprocesses.
Assertivelygrowcross-platformimperativesvis-a-visproactivetechnologies.
Convenientlyempowermultidisciplinarymeta-serviceswithoutenterprise-wideinterfaces.
Convenientlystreamlinecompetitivestrategicthemeareaswithfocusede-markets.
Phosfluorescentlysyndicateworld-classcommunitiesvis-a-visvalue-addedmarkets.
Appropriatelyreinventholisticservicesbeforerobuste-services.
Copyrightnoticegoeshere