Anda di halaman 1dari 11

1/20/2015

25CSSbestpracticeswefollow

Therecanbemultiplereasonsforadeveloperfornotapplyingthesegoodpracticesbutwearenot
goingtodelveintothat.AtInnofied,itisneveroptionaltoimplementthebestpracticesandwealways
makesurethateveryFrontenddeveloperadherestothese.Thefollowing25pointsarelifesaversfor
anyCSSdeveloperandshouldbefollowedasmuchaspossible.

1.StayOrganized
Keepyourselforganizeditalwayspaysoff.Ratherthanhaphazardlydroppinginidsandclassesin
theorderinwhichtheycometomind,useacoherentstructure.Itwillhelpyoukeepthecascadingpart
ofCSSinmindandsetsyourstylesheetuptotakeadvantageofstyleinheritance.
Declareyourmostgenericitemsfirst,thenthenotsogenericonesandsoon.ThisletsyourCSS
properlyinheritattributesandmakesitmucheasierforyoutooverrideaspecificstylewhenyouneed
to.YoullbefasterateditingyourCSSlaterbecauseitwillfollowaneasytoread,logicalstructure.
Useastructurethatworksbestforyouwhilekeepingfutureeditsandotherdevelopersinmind.
1. Resetsandoverrides
2. Linksandtype
3. Mainlayout
4. Secondarylayoutstructures
5. Formelements
6. Miscellaneous

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

1/11

1/20/2015

25CSSbestpracticeswefollow

2.UseUsefulNamingConventions
YoucannoticeintheaboveexamplewhereIdeclaredacoupleofcolumnidsandcalledthemcallout
alphaandcalloutbeta.Whynotjustcallthemcolleftandcolright?Thinkoffutureedits,always.Next
yearyoumayneedtoredesignyoursiteandmovethatleftcolumntotheright.Youshouldnthaveto
renametheelementinyourHTMLandrenametheidinyourstylesheetjusttochangeitsposition.
Sure,youcouldjustrepositionthatleftcolumntotherightandkeeptheidas#colleft,buthow
confusingisthat?Iftheidsaysleft,oneshouldexpectthatitwillalwaysbeontheleft.Thisdoesnt
leaveyoumuchroomtomovethingsaroundlateron.
OneofthemajoradvantagesofCSSistheabilitytoseparatestylesfromcontent.Youcanredesign
data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

2/11

1/20/2015

25CSSbestpracticeswefollow

yoursiteentirelybyjustmodifyingtheCSSwithoutevertouchingtheHTML.Sodontmuckupyour
CSSbyusinglimitingnames.Usemoreversatilenamingconventionsandstayconsistent.
Leavepositionorstylespecificwordsoutofyourstylesandids.Aclassof.linkbluewilleithermake
moreworkforyou,ormakeyourstylesheetreallymessywhenyourclientlaterasksyoutochange
thosebluelinkstoorange.Nameyourelementsbasedonwhattheyare,notwhattheylooklike.For
example,.commentblueismuchlessversatilethan.commentbeta,and.postlargefontismorelimiting
than.posttitle.

3.HyphensInsteadofUnderscoresforCSSclasses
GetintothehabitofusinghyphensinsteadwhilewritingCSSclassesandunderscoreforelementIDs.
Exampleclass:.profileimage
ExampleID:#user_image

4.DontRepeatYourself
Reuseattributeswheneverpossiblebygroupingelementsinsteadofdeclaringthestylesagain.Ifyour
h1andh2elementsbothusethesamefontsize,colorandmargins,groupthemusingacomma.

5.Createalogicalstructurefirst
Ifyouareabeginner,youarelikelytofeeltheurgetojumpintocodingwithoutplanningmuchabout
whatyouaregoingtocreate.Thisleadstoproblemsonceyouarehalfwayandsomenewchanges
come.Youshouldalwaysfirstcreatealogicalstructureforhowyouwanttoseethepage.Even
experienceddevelopersatfirsteithergoforsomesketchesorwireframes(whiledesignisntpresent)
andthentheymovetodevelopment.So,theprocessshouldbesomethinglikethis:
data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

3/11

1/20/2015

25CSSbestpracticeswefollow

1. Drawthelayout(logicalstructure)first
2. CreateanHTMLstructurethatwillsupportthelayout
3. StartworkingonCSS
Asamplelayoutstructureisgivenbelow:

6.OrganizeyourCSSstyles,usingflags
Letmequotetheexperts.
Divideyourstylesheetintospecificsections:i.e.GlobalStyles(body,paragraphs,lists,etc),Header,
PageStructure,Headings,TextStyles,Navigation,Forms,Comments,andExtras.[5Tipsfor
OrganizingYourCSS]
1 /**/
2 /*>>>GLOBAL<<<*/
3 /**/

Separatecodeintoblocks.ThismightbecommonsensetosomeofyoubutsometimesIlookat
CSSanditsnotbrokendownintosections.Itseasytodoanditmakesworkingwithcodeweeks,
months,oryearslatermucheasier.Youllhaveaneasiertimefindingclassesandelementsthatyou
needtochange.

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

4/11

1/20/2015

25CSSbestpracticeswefollow

Examples:/*Structure*/,/*Typography*/etc.[CSSTipsandTricks]

7.BecomeFamiliarWithEveryProperty
WhileyoudontneedtouseeverypropertythatexistsinCSS,itisagoodideatoatleastknowwhat
mostofthemdo.Forthis,youcantakealookattheCSSpropertyreference,fromHTMLDog.

8.UseShorthandCSS
Imaginehavingtowritethefollowingcode,ifyouwanttohaveadifferentmarginforeachsideofadiv.
1
2
3
4

margintop:10px
marginright:24px
marginbottom:12px
marginleft:0

Thatwouldtakealotoftimeeverytimeyouwanttohavesomethinglikethatappliedtoabox,right?
ThankstothemagicofshorthandCSS,thatcodecanbecondensedintoasingleline.
1 margin:10px24px12px0

Now,thatsmuchquickerright!Justremember:theorderofthesidesgoesclockwise,fromthetop.So
itstop,right,bottom,left.
FormoreonusingshorthandCSS,checkoutthisawesomearticleatWebtint.

9.AvoidUsingInlineStyles
Byinlinestyles,ImeanthestyleattributeintheHTMLtags.Youshouldavoidusingitbecauseitmixes
upcontentandpresentation,whichcanleadtomoretrouble.
UsinginlinestylesisreallyalmostasbadasusingpurelypresentationHTMLelementssuchasfont.It
leadstomessycodewhereeachHTMLfilewillneedtobeupdatedintheeventofastylechange,
insteadofaglobalchangeinasingleexternalstylesheet.
Bad:
1 <divstyle="background:red">
2 Ipsumschmipsum
3 </div>

Good:
1
2
3
4

.infobox{
background:red
}

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

5/11

1/20/2015

25CSSbestpracticeswefollow

5 <divclass="infobox">
6 Ipsumschmipsum
7 </div>

10.UseanExternalStylesheet
Usinganexternalstylesheetisveryuseful.PutallofyourCSSinanexternalfile,andhaveitincludedin
yourHTML.Thisisprobablythebestwaytobesuretokeepcontentandpresentationseparate.
Advantagesofusinganexternalstylesheet:
Ithelpstoseparatecontentfrompresentation.
Externalstylesheetscanbecached,allowingfasterpageloadingtimes.
Asinglestylesheetcanbeappliedtoeverypageofasite,allowingquickstylechangestoasingle
file.
Itmakesorganizationmucheasier.
Touseanexternalstylesheet,simplyplacethefollowingcodeinbetweenyourheadtags.Besureto
replacestyle.csswithyourCSSfile.
1 <linkrel="stylesheet"href="style.css"type

11.UseaReset
MostCSSframeworkshavearesetbuiltin,butifyourenotgoingtouseonethenatleastconsider
usingareset.Resetsessentiallyeliminatebrowserinconsistenciessuchasheights,fontsizes,margins,
headings,etc.Theresetallowsyourlayoutlookconsistentinallbrowsers.
TheMeyerWebisapopularreset,alongwithYahoosdeveloperreset.Oryoucouldalwaysrollyour
ownreset,ifthatticklesyourfancy.

12.KeepaColorReference
Ibetthishashappenedtoyoumanytimes,whenyoureworkingonawebsitedesignandyoucant
exactlyrememberthehexadecimalcolorcodeforeachelementofthedesign.
AwaytofixthatistoincludeacolorreferenceatthetopofyourCSSfile.Thatway,ifyouforgetthe
codeforaspecificcolor,youcansimplycheckthetopofthefile,thensimplycopyandpasteitinto
anothersectionofyourfile.
1
2
3

/*Colourreference

background:#FFCCCC

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

6/11

1/20/2015

4
5
6
7
8
9
10

25CSSbestpracticeswefollow

normaltext:#FFF46D
links:#38FF0E
headings:#77F6FF
maincontentbg:#DCAFFF

Note:Donotusethiscolorschemeinarealdesign.Itwilllookhorrible.
*/

13.CreateYourHTMLFirst
ManydesignerscreatetheirCSSatthesametimetheycreatetheHTML.Itseemslogicaltocreate
bothatthesametime,butactuallyyoullsaveevenmoretimeifyoucreatetheentireHTMLmockup
first.Thereasoningbehindthismethodisthatyouknowalltheelementsofyoursitelayout,butyou
dontknowwhatCSSyoullneedwithyourdesign.CreatingtheHTMLlayoutfirstallowsyoutovisualize
theentirepageasawhole,andallowsyoutothinkofyourCSSinamoreholistic,topdownmanner.

14.UseMultipleClasses
Sometimesitsbeneficialtoaddmultipleclassestoanelement.Letssaythatyouhavea<div>box
thatyouwanttofloatright,andyouvealreadygotaclass.rightinyourCSSthatfloatseverythingtothe
right.Youcansimplyaddanextraclassinthedeclaration,likeso:
1 <divclass="boxright"></div>

Youcanaddasmanyclassesasyoudlike(spaceseparated)toanydeclaration.
Beverycarefulwhileusingidsandclassnameslikeleftandright.Iwillusethem,butonlyforthings
suchasblogposts.Howcome?Letsimaginethat,downtheroad,youdecidethatyoudratherseethe
boxfloatedtotheLEFT.Inthiscase,youdhavetoreturntoyourHTMLandchangetheclassname
allinordertoadjustthepresentationofthepage.Thisisunsemantic.RememberHTMLisformarkup
andcontent.CSSisforpresentation.
IfyoumustreturntoyourHTMLtochangethepresentation(orstyling)ofthepage,
youredoingitwrong!

15.CommentyourCSS
Justlikeanyotherlanguage,itsagreatideatocommentyourcodeinsections.Toaddacomment,
simplyadd/*behindthecomment,and*/tocloseit,likeso:
/*HereshowyoucommentCSS*/

16.UnderstandtheDifferencebetweenBlockvs.
InlineElements
data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

7/11

1/20/2015

25CSSbestpracticeswefollow

Blockelementsareelementsthatnaturallycleareachlineaftertheyredeclared,spanningthewhole
widthoftheavailablespace.Inlineelementstakeonlyasmuchspaceastheyneed,anddontforcea
newlineaftertheyreused.
Herearethelistsofelementsthatareeitherinlineorblock:
span,a,strong,em,img,br,input,abbr,acronym
Andtheblockelements:
div,h1h6,p,ul,li,table,blockquote,pre,form

17.MakeUseofGenericClasses
Youllfindthattherearecertainstylesthatyoureapplyingoverandover.Insteadofaddingthat
particularstyletoeachID,youcancreategenericclassesandaddthemtotheIDsorotherCSS
classes(usingtip#8).
Forexample,Ifindmyselfusingfloat:rightandfloat:leftoveranoverinmydesigns.SoIsimplyaddthe
classes.leftand.righttomystylesheet,andreferenceitintheelements.
1
2
3
4

.left{float:left}
.right{float:right}

<divid="coolbox"class="left">...</div>

Thiswayyoudonthavetoconstantlyaddfloat:lefttoalltheelementsthatneedtobefloated.

18.UseMargin:0autotoCenterLayouts
Manybeginnerscantfigureoutwhyyoucantsimplyusefloat:centertoachievethatcenteredeffecton
blocklevelelements.Ifonlyitwerethateasy!Unfortunately,youllneedtousethefollowingcodeto
centerdivs,paragraphsorotherelementsinyourlayout.
1 margin:0auto//top,bottomandleft,

BydeclaringthatboththeleftANDtherightmarginsofanelementmustbeidentical,the
havenochoicebuttocentertheelementwithinitscontainingelement.

19.DontJustWrapaDIVAroundIt
Whenstartingout,theresatemptationtowrapadivwithanIDorclassaroundanelementandcreate
astyleforit.
data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

8/11

1/20/2015

25CSSbestpracticeswefollow

1 <div><h1>HeaderText</h1></div>

Sometimesitmightseemeasiertojustcreateuniqueelementstylesliketheaboveexample,butyoull
starttoclutteryourstylesheet.Thiswouldhaveworkedjustfine:
1 <h1>HeaderText</h1>

Thenyoucaneasilyaddastyletotheh1insteadofaparentdiv.

20.UseFirebug
IfyouareusingFirefoxandyouhaventdownloadedFirebugyet,stopandgodoit.Seriously.Thislittle
toolisamusthaveforanywebdeveloper.Amongthemanyfeaturesthatcomebundledwiththe
Firefoxextension(debugJavaScript,inspectHTML,finderrors),youcanalsovisuallyinspect,modify,
andeditCSSinrealtime.YoucanlearnmoreaboutwhatFirebugdoesontheofficialFirebug
website.PresentlyFirefoxcameupwithitsowndebuggingtoolso,youcanuseeitherofthemtohave
thesamepurpose.
IfyouareusingChrome,thenyoualreadyhaveawesomeDeveloperToolsthatworkexactlysimilarto
Firebug.

21.DontUnderestimatetheList
Listsareagreatwaytopresentdatainastructuredformatthatseasytomodifythestyle.Thanksto
thedisplayproperty,youdonthavetojustusethelistasatextattribute.Listsarealsogreatfor
creatingnavigationmenusandthingsofthesort.
Manybeginnersusedivstomakeeachelementinthelistbecausetheydontunderstandhowto
properlyutilizethem.Itswellworththeefforttousebrushuponlearninglistelementstostructuredata
inthefuture.
Youlloftenseenavigationlinkslike:
1
2
3
4
5
6
7

<ahref="http://innofied.com">Home</a>

<ahref="http://innofied.com/aboutus">About

<ahref="http://innofied.com/portfolio">Portfolio

<ahref="http://innofied.com/contactus">Contact

Though,technicallythiswillworkjustfineafterabitofCSS,itssloppy.Ifyoureaddingalistoflinks,
useanunorderedlist,sillygoose!

22.AvoidExtraSelectors
data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%20

9/11

1/20/2015

25CSSbestpracticeswefollow

ItseasytounknowinglyaddextraselectorstoourCSSthatcluttersthestylesheet.Onecommon
exampleofaddingextraselectorsiswithlists.
1 body#container.someclassulli{....}

Inthisinstance,justthe.someclassliwouldhaveworkedjustfine.
1 .someclassli{...}

AddingextraselectorswontbringArmageddonoranythingofthesort,buttheydokeepyourCSSfrom
beingassimpleandcleanaspossible.

23.Usemultiplestylesheets
Dependingonthecomplexityofthedesignandthesizeofthesite,itssometimeseasiertomake
smaller,multiplestylesheetsinsteadofonegiantstylesheet.Asidefromitbeingeasierforthedesigner
tomanage,multiplestylesheetsallowyoutoleaveoutCSSoncertainpagesthatdontneedthem.
Forexample,Imighthaveapollingprogramthatwouldhaveauniquesetofstyles.Insteadofincluding
thepollstylestothemainstylesheet,Icouldjustcreateapoll.cssandthestylesheetonlytothepages
thatshowthepoll.
However,besuretoconsiderthenumberofHTTPrequeststhatarebeingmade.Many
designersprefertodevelopwithmultiplestylesheets,andthencombinethemintoonefile.
ThisreducesthenumberofHTTPrequeststoone.Also,theentirefilewillbecachedon
theuserscomputer.

24.Useamasterstylesheet
Letmequotethispieceofadvicefromitsoriginalsource:
OneofthemostcommonmistakesIseebeginnersandintermediatesfallvictimtowhenitcomesto
CSSisnotremovingthedefaultbrowserstyling.Thisleadstoinconsistenciesintheappearanceofyour
designacrossbrowsers,andultimatelyleavesalotofdesignersblamingthebrowser.Itisamisplaced
blame,ofcourse.Beforeyoudoanythingelsewhencodingawebsite,youshouldresetthestyling.
[MasterStylesheet:TheMostUsefulCSSTechnique],[RyanParr]
1
2
3
4
5
6

master.css
CSS
@importurl("reset.css")
@importurl("global.css")
@importurl("flash.css")
@importurl("structure.css")
<styletype="text/css"media="Screen">/*\*/

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%2

10/11

1/20/2015

25CSSbestpracticeswefollow

25.KeepalibraryofhelpfulCSSclasses
Usefulfordebugging,butshouldbeavoidedinthereleaseversion(separatemarkupandpresentation).
Sinceyoucanusemultipleclassnames(i.e.<p></p>),makeuseofthemwhiledebuggingyour
markup.(updated)[RichardK.Miller]
1
2
3
4
5
6
7

.width100{width:100%}
.width75{width:75%}
.width50{width:50%}
.floatLeft{float:left}
.floatRight{float:right}
.alignLeft{textalign:left}
.alignRight{textalign:right}

data:text/htmlcharset=utf8,%3Cp%20style%3D%22margin%3A%200px%200px%2022px%3B%20padding%3A%200px%3B%20border%3A%200px%2

11/11

Anda mungkin juga menyukai