|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
结构清晰,容易被搜索引擎搜索到,天生优化了seo
网页制造poluoluo文章简介:英文教程:CSS的Float.
Whatis“Float”?
FloatisaCSSpositioningproperty.Tounderstanditspurposeandorigin,wecanlooktoprintdesign.Inaprintlayout,imagesmaybesetintothepagesuchthattextwrapsaroundthemasneeded.Thisiscommonlyandappropriatelycalled“textwrap”.Hereisanexampleofthat.
Inpagelayoutprograms,theboxesthatholdthetextcanbetoldtohonorthetextwrap,ortoignoreit.Ignoringthetextwrapwillallowthewordstoflowrightovertheimagelikeitwasn’teventhere.Thisisthedifferencebetweenthatimagebeingpartoftheflowofthepage(ornot).Webdesignisverysimilar.
Inwebdesign,pageelementswiththeCSSfloatpropertyappliedtothemarejustliketheimagesintheprintlayoutwherethetextflowsaroundthem.Floatedelementsremainapartoftheflowofthewebpage.Thisisdistinctlydifferentthanpageelementsthatuseabsolutepositioning.Absolutelypositionedpageelementsareremovedfromtheflowofthewebpage,likewhenthetextboxintheprintlayoutwastoldtoignorethepagewrap.Absolutelypositionedpageelementswillnotaffectthepositionofotherelementsandotherelementswillnotaffectthem,whethertheytoucheachotherornot.
SettingthefloatonanelementwithCSShappenslikethis:Therearefourvalidvaluesforthefloatproperty.LeftandRightfloatelementsthosedirectionsrespectively.None(thedefault)ensurestheelementwillnotfloatandInheritwhichwillassumethefloatvaluefromthatelementsparentelement.
Whatarefloatsusedfor?
Asidefromthesimpleexampleofwrappingtextaroundimages,floatscanbeusedtocreateentireweblayouts.
Floatsarealsohelpfulforlayoutinsmallerinstances.Takeforexamplethislittleareaofawebpage.Ifweusefloatforourlittleavatarimage,whenthatimagechangessizethetextintheboxwillreflowtoaccomodate:
Thissamelayoutcouldbeaccomplishedusingrelativepositioningoncontainerandabsolutepositioningontheavataraswell.Indoingitthisway,thetextwouldbeunafftedbytheavatarandnotbeabletoreflowonasizechange.
ClearingtheFloat
Float’ssisterpropertyisclear.Anelementthathastheclearpropertysetonitwillnotmoveupadjacenttothefloatlikethefloatdesires,butwillmoveitselfdownpastthefloat.Againanillustrationprobablydoesmoregoodthanwordsdo.
Intheaboveexample,thesidebarisfloatedtotherightandisshorterthanthemaincontentarea.Thefooterthenisrequiredtojumpupintothatavailablespaceasisrequiredbythefloat.Tofixthisproblem,thefootercanbeclearedtoensureitstaysbeneathbothfloatedcolumns.Clearhasfourvalidvaluesaswell.Bothismostcommonlyused,whichclearsfloatscomingfromeitherdirection.LeftandRightcanbeusedtoonlyclearthefloatfromonedirectionrespectively.Noneisthedefault,whichistypicallyunnecessaryunlessremovingaclearvaluefromacascade.Inheritwouldbethefifth,butisstranglynotsupportedinInternetExplorer.Clearingonlytheleftorrightfloat,whilelesscommonlyseeninthewild,definitelyhasitsuses.
TheGreatCollapse
Oneofthemorebewilderingthingsaboutworkingwithfloatsishowtheycanaffecttheelementthatcontainsthem(their“parent”element).Ifthisparentelementcontainednothingbutfloatedelements,theheightofitwouldliterallycollapsetonothing.Thisisn’talwaysobviousiftheparentdoesn’tcontainanyvisuallynoticeablebackground,butitisimportanttobeawareof.
Asanti-intuitiveascollapsingseemstobe,thealternativeisworse.Considerthisscenario:
Iftheblockelementontopwheretohaveautomaticallyexpandedtoaccomodatethefloatedelement,wewouldhaveanunnaturalspacingbreakintheflowoftextbetweenparagraphs,withnopracticalwayoffixingit.Ifthiswerethecase,usdesignerswouldbecomplainingmuchharderaboutthisbehaviorthanwedoaboutcollapsing.
Collapsingalmostalwaysneedstobedealtwithtopreventstrangelayoutandcross-browserproblems.Wefixitbyclearingthefloatafterthefloatedelementsinthecontainerbutbeforethecloseofthecontainer.
TechniquesforClearingFloats
Ifyouareinasituationwhereyoualwaysknowwhatthesucceedingelementisgoingtobe,youcanapplytheclear:both;valuetothatelementandgoaboutyourbusiness.Thisisidealasitrequiresnofancyhacksandnoadditionalelementsmakingitperfectlysemantic.Ofcoursethingsdon’ttypicallyworkoutthatwayandweneedtohavemorefloat-clearingtoolsinourtoolbox.
- TheEmptyDivMethodis,quiteliterally,anemptydiv.<divstyle="clear:both;"><div>.Sometimesyou’llseea<br/>elementorsomeotherrandomelementused,butdivisthemostcommonbecauseithasnobrowerdefaultstyling,doesn’thaveanyspecialfunction,andisunlikelytobegenericallystyledwithCSS.Thismethodisscornedbysemanticpuristssinceitspresencehasnocontexualmeaningatalltothepageandistherepurelyforpresentation.Ofcourseinthestrictestsensetheyareright,butitgetsthejobdonerightanddoesn’thurtanybody.
- TheOverflowMethodreliesonsettingtheoverflowCSSpropertyonaparentelement.Ifthispropertyissettoautoorhiddenontheparentelement,theparentwillexpandtocontainthefloats,effectivelyclearingitforsucceedingelements.Thismethodcanbebeautifullysemanticasitmaynotrequireanadditionalelements.Howeverifyoufindyourselfaddinganewdivjusttoapplythis,itisequallyasunsemanticastheemptydivmethodandlessadaptable.Alsobearinmindthattheoverflowpropertyisn’tspecificallyforclearingfloats.Becarefulnottohidecontentortriggerunwantedscrollbars.
- TheEasyClearingMethodusesacleverCSSpseduoselector(:after)toclearfloats.Ratherthansettingtheoverflowontheparent,youapplyanadditionalclasslike“clearfix”toit.ThenapplythisCSS:
- .clearfix:after{content:".";visibility:hidden;display:block;height:0;clear:both;}
复制代码 Thiswillapplyasmallbitofcontent,hiddenfromview,aftertheparentelementwhichclearsthefloat.Thisisn’tquitethewholestory,asadditionalcodeneedstobeusedtoaccomodateforolderbrowsers.
Differentscenarioscallfordifferentfloatclearningmethods.Takeforexampleagridofblocks,eachofdifferenttypes.
Tobettervisuallyconnectthesimilarblocks,wewanttostartanewrowasweplease,inthiscasewhenthecolorchanges.Wecoulduseeithertheoverfloworeasyclearningmethodifeachofthecolorgroupshadaparentelement.Or,weusetheemptydivmethodinbetweeneachgroup.Threewrappingdivsthatdidn’tpreviouslyexistorthreeafterdivsthatdidn’tpreviouslyexist.I’llletyoudecidewhichisbetter.
ProblemswithFloats
Floatsoftengetbeatonforbeingfragile.ThemajorityofthisfragilitycomesfromIE6andtheslewoffloat-relatedbugsithas.AsmoreandmoredesignersaredroppingsupportforIE6,youmaynotcare,butforthefolksthatdocarehereisaquickrundown.
- Pushdownisasymptomofanelementinsideafloateditembeingwiderthanthefloatitself(typicallyanimage).Mostbrowserswillrendertheimageoutsidethefloat,butnothavethepartstickingoutaffectotherlayout.IEwillexpandthefloattocontaintheimage,oftendrasticallyaffectinglayout.Acommonexampleisanimagestickingoutofthemaincontentpushthesidebardownbelow.
Quickfix:Makesureyoudon’thaveanyimagesthatdothis,useoverflow:hiddentocutoffexcess.
- DoubleMarginBug–AnotherthingtorememberwhendealingwithIE6isthatifyouapplyamargininthesamedirectionasthefloat,itwilldoublethemargin.Quickfix:setdisplay:inlineonthefloat,anddon’tworryitwillremainablock-levelelement.
- The3pxJogiswhentextthatisupnexttoafloatedelementismysteriouslykickedawayby3pxlikeaweirdforcefieldaroundthefloat.Quickfix:setawidthorheightontheaffectedtext.
- InIE7,theBottomMarginBugiswhenifafloatedparenthasfloatedchildreninsideit,bottommarginonthosechildrenisignoredbytheparent.Quickfix:usingbottompaddingontheparentinstead.
Alternatives
Ifyouneedtextwrappingaroundimages,therereallyaren’tanyalternativesforfloat.Speakingofwhich,checkoutthisratherclevertechniqueforwrappingtextaroundirregularshapes.Butforpagelayout,theredefinitelyarechoices.EricSolrighthereonAListAparthasanarticleonFauxAbsolutePositioning,whichisaveryinterestingtechniquethatinmanywayscombinestheflexibilityoffloatswiththestrengthofabsolutepositioning.CSS3hastheTemplateLayoutModulethat,whenwidelyadopted,willprovetobethepagelayouttechniqueofchoice.
在Div+CSS标准化的影响下,网页设计人员已经把这一要求作为行业标准。那么什么是Div+CSS标准?Div+CSS的标准化设计到底有什么好处? |
|