CSS Crib Sheet
It's clear to anyone who has tried building a site or two with CSS that browser support still isn't perfect. In fact, depending on the complexity of your work, you may end up banging your head on your desk and swearing off Web design forever, for the sake of a nice, simple job like city planning or nuclear physics.
Inthatvein,it'simportanttorealizethatyou'renotalone.Awholecommunityisworkingouttheproblemswithstandards-baseddesignandsharingtheknowledgewithoneanother.
CoordinatedbycoauthorDaveShea,oneofthemanyresourcesnowavailableiscalledtheCSSCribSheet.Designedasaone-stopresourceforcommonproblemsandsolutions,theCribSheetisduplicatedbelow.Themostrecentversionisavailableatwww.mezzoblue.com/css/cribsheet.
Whenindoubt,validate-若不确信,那么就去验证
Whendebugging,youmaysaveyourselfheadachesbysimplyvalidatingyourcodefirst.ImproperlyformedXHTML/CSSwillcausemanyalayoutglitch.Validationisanimportanttoolforlearninghowtofindandcorrectmistakes.TheW3ChostsbothXHTMLandCSSvalidators,availableathttp://validator.w3.organdhttp://jigsaw.w3.org/css-validatorrespectively.
Notethaterrorsearlyoninthedocumentmaycausefurthererrorselsewhereduetoimpropernestingorotherreasons,whichareoftennottrueerrors.Werecommendfixingafewobviouserrorsandre-validating;youmightfindthetotalerrorcountdrasticallyreduced.
BuildandtestyourCSSinthemostadvancedbrowseravailablebeforetestinginothers,notafter-创建并测试css时,首先在最高级,最先进的浏览器中进行,然后再考虑其它浏览器
Ifyoubuildasitebytestingitinanolderbrowser,yourcodewillenduprelyingonthelessadvancedandpotentiallybrokenrenderingofthatbrowser.Youwilllikelybefrustratedwhenamorestandards-compliantbrowserrendersitimproperly,whichiscompletelybackward.
Instead,startwithperfectionandthentestforthelessablebrowsers.Yourcodewillbemorestandards-compliantfromthestart,andyouwon'tneedtogotogreatlengthstosupportotherbrowsers.TodaythismeansyoushouldtestinMozilla(Firefox),Safari,orperhapsOperafirst,andthencorrectforMicrosoftInternetExplorer.
Whenrelyingonfloatsforlayouts,makesuretheyclearproperly-若用浮动实现布局,请确保正确地清除了浮动
Floatsaretricky,andtheydon'talwaysdowhatyouexpect.Ifyourunintoasituationwhereafloatedelementextendspasttheborderofitscontainingelementorjustdoesn'tbehaveproperly,makesurethatwhatyou'reattemptingtodoiscorrect.SeeEricMeyer'stutorialonthematterathisComplexSpiralConsultingWebsite(www.complexspiral.com/publications/containing-floats).
Marginscollapse;applypaddingorabordertoavoid-为元素应用内边距或边框来避免外边距重叠
Youmaystrugglewithextrawhitespacewhereyoudon'twantany,ornowhitespacewhereyouactuallywantsome.Ifyou'reusingmargins,collapsingismostlikelytheculprit.AndyBuddexplainswhatyoucanexpectonhisWebsite(www.andybudd.com/archives/2003/11/no_margin_for_error).
Trytoavoidapplyingpadding/bordersandaspecificwidthorheighttoanelement-避免同时为元素指定明确的内边距、边框值与宽度、高度值
InternetExplorer5.0and5.5forWindowsgettheboxmodelwrong,whichoftencausesproblemswhenrelyingonwidthorheightvalues.Therearewaysaroundthis(seehttp://tantek.com/CSS/Examples/boxmodelhack.html),butit'sbesttosidesteptheissueifpossiblebysimplyapplyingamargintochildelementsifaparentrequiresaspecificwidth/height,orapplyingpaddingtotheparentifthechildrequiresthewidth/height.
Avoidthe"FlashofUnstyledContent"inInternetExplorer6forWindows-避免IE6“无样式内容瞬间”现象
Ifyourelyon@importaloneforexternalstyle,soonerorlateryou'llnoticethatInternetExplorer6forWindows"flashes"plain,unformattedHTMLbrieflybeforeapplyingCSS.Thiscanbeavoidedbylinkingyourstylesheet,oraddingascriptelementtoyourpage.SeeBlueRobot.com's"FlashofUnstyledContent"page(www.bluerobot.com/web/css/fouc.asp).
Don'trelyonmin-width/min-height-不要依靠min-width或min-height属性
IE/Windoesn'tsupporteither.Butitdoestreatwidthandheightasiftheyweremin-widthormin-height,toacertaindegree,sowithabitoffilteringspecifictoInternetExplorerforWindows,youcanachievethesameendresultusingwidthorheightalone.Foraspecificexample,see"min-height:fixed"atmezzoblue.com(mezzoblue.com/archives/2004/09/16/minheight_fi).
Whenindoubt,decreasepercentagevalues-尝试减少百分比值
Sometimesroundingerrorswillcause50%+50%toaddupto100.1%,whichendsupbreakinglayouts.Trybumpingthevaluesdownfrom50%to49%,oreven49.9%.
ContentnotshowingupproperlyinInternetExplorer?-IE中没有完整的显示出内容
Youmaybesufferingthe"Peekaboobug,"especiallyifitshowsupwhentheuserhoversthepointeroveralink.SeePositionIsEverything(www.positioniseverything.net/explorer/peekaboo.html)forthefix.
Makesureyourdesiredeffectactuallyexists-确保要实现的效果确实存在
Therearebrowser-specificCSSextensionsthataren'tintheofficialspec.Filtersandscroll-barformattingareproprietarycodeelementsthatwon'tworkinanythingbutInternetExplorer,forexample.Ifthevalidatortellsyouthecodeyou'reusingisn'tdefined,chancesareit'sproprietaryandwon'tworkconsistentlyacrossotherbrowsers.
Remember"LoVe/HAte"linking-牢记LoVe/HAte(爱恨)链接规则
Whenspecifyinglinkpseudo-classes,alwaysdosointhisorder:link,visited,hover,active.Anyotherorderwon'tworkconsistently.Considerusing:focusaswell,andmodifytheordertoLVHFA(andrememberthissequencewithMattHaughey'ssuggestedmnemonic"LordVader'sHandleFormerlyAnakin").
Remember"TRouBLed"shorthand-牢记TRouBLED(麻烦的)边框简写顺序
border,margin,andpaddingshorthandassumesaspecificorder,clockwisefromthetop:top,right,bottom,left.Somargin:01px3px5px;resultsinnotopmargin,a1-pixelrightmargin,andsoon.Rememberthemnemonic"TRouBLe"andyou'llalwaysgetthecorrectorder.
Specifyunitsfornon-zerovalues-为非零值标明单位
CSSrequiresyoutospecifyunitsonallvaluesoffonts,margins,andsizes.(Theonlyexceptionisline-height,whichdoesn'trequireaunitbutcanacceptoneanyway.)Thebehaviorofanyparticularbrowserwhensizesaren'tspecifiedshouldnotbereliedupon.Zeroiszero,however,beitpx,em,oranythingelse;nounitsarenecessarywhenthevalueis0.Example:padding:02px01em;
Testdifferentfontsizes-测试不同字体的大小显示
AdvancedbrowserslikeMozillaandOperaallowtheusertoresizetextnomatterwhichsizingunitisused.Someuserswillassuredlyhaveadifferentlysizeddefaultthanyou;trytoaccommodateaswidearangeaspossibletoaccountforthesevariations.
MatchcasesbetweenyourHTMLandCSS-在HTML和CSS中统一大小写
CSS,andmostbrowsers,arecase-sensitive.Applyingaclasslike'homePage'isfine,providedyouareconsistentwithyourlettercaseacrossbothCSSandHTML.Applyingstylerulesto'homepage'insteadwillcauseproblemsinuseragentsthatcloselyfollowtheCSSspecification(likeMozilla).
Testembedded;launchimported-测试时实用嵌入样式,发布时再改为外部链接方式
IfyoudevelopwithastylesheetembeddedbetweenstyletagswithinyourHTMLsource,youeliminateanypotentialcachingerrorswhiletesting.Thiscanbeveryimportantwhenworkingwithsomeolderbrowsers.ButmakesuretomoveyourCSStoanexternalfilebeforelaunching,importedwith@importorlink;otherwise,thebenefitsofexternalCSSarelost.
Addobviousborderstohelpdebuglayouts-用明显的边框辅助调试布局
Auniversalrulelike*{border:solid1px#f00;}cangoalongwaytowardpinpointingalayoutproblem.Addingabordertospecificelementscanhelpidentifyoverlappingandextrawhitespace,whichmightnototherwisebeobvious.
Don'tusesinglequotationmarksaroundpathsforimages-指定图片路径时不要实用单引号
Whenplacingabackgroundimage,quotemarksareunnecessary,andInternetExplorer5forMacintoshwon'tpickuptheimage.Usedoublequotes,ornoneatall.
Becarefulwhenstylinglinksifyou'reusinganchors-若实用了锚点(anchor),那么在为超链接应用样式时要格外小心
Ifyouuseaclassicanchorinyourcodeaname="anchor"you'llnoticethatitpicksup:hoverand:activepseudo-classes.Toavoidthis,you'llneedtouseanidforanchorsinsteaddivid="anchor"orstylewithaslightlymorearcanesyntax,:link:hoverand:link:active.Seewww.dbaron.org/css/1999/09/links.
Don'tlinktoemptystylesheetsas"placeholders"forfuturestylesheets(likehandheldorprintmediastylesheets)-不要链接空的样式表作为“占位符”(例如手持设备或应用于打印的样式表)
Internet Explorer 5 for Mac takes issue with the empty style sheet, and the page load time increases. Instead, have at least one rule (or perhaps even a comment) in the style sheet, or simply don't link to it.