Airbnb CSS / Sass Styleguide
Airbnb CSS / Sass Styleguide
Airbnb CSS / Sass Styleguide
Terminology
Ruledeclaration
Aruledeclarationisthenamegiventoaselector(oragroupofselectors)withanaccompanyinggroupof
properties.Heresanexample:
.listing{
fontsize:18px;
lineheight:1.2;
}
Selectors
Inaruledeclaration,selectorsarethebitsthatdeterminewhichelementsintheDOMtreewillbestyledby
thedefinedproperties.SelectorscanmatchHTMLelements,aswellasanelementsclass,ID,oranyofits
attributes.Herearesomeexamplesofselectors:
.myelementclass{
/*...*/
[ariahidden]{
/*...*/
}
Properties
Finally,propertiesarewhatgivetheselectedelementsofaruledeclarationtheirstyle.Propertiesarekeyvalue
pairs,andaruledeclarationcancontainoneormorepropertydeclarations.Propertydeclarationslooklikethis:
/*someselector*/{
background:#f1f1f1;
color:#333;
CSS
Formatting
Usesofttabs(2spaces)forindentation
PreferdashesovercamelCasinginclassnames.
UnderscoresandPascalCasingareokayifyouareusingBEM(seeOOCSSandBEMbelow).
DonotuseIDselectors
Whenusingmultipleselectorsinaruledeclaration,giveeachselectoritsownline.
Putaspacebeforetheopeningbrace { inruledeclarations
Inproperties,putaspaceafter,butnotbefore,the : character.
Putclosingbraces } ofruledeclarationsonanewline
Putblanklinesbetweenruledeclarations
Bad
.avatar{
borderradius:50%;
border:2pxsolidwhite;}
.no,.nope,.not_good{
//...
}
#lolno{
//...
Good
.avatar{
borderradius:50%;
border:2pxsolidwhite;
}
.one,
.selector,
.perline{
//...
}
Comments
Preferlinecomments( // inSassland)toblockcomments.
Prefercommentsontheirownline.Avoidendoflinecomments.
Writedetailedcommentsforcodethatisntselfdocumenting:
Usesofzindex
Compatibilityorbrowserspecifichacks
OOCSSandBEM
WeencouragesomecombinationofOOCSSandBEMforthesereasons:
Ithelpscreateclear,strictrelationshipsbetweenCSSandHTML
Ithelpsuscreatereusable,composablecomponents
Itallowsforlessnestingandlowerspecificity
Ithelpsinbuildingscalablestylesheets
OOCSS,orObjectOrientedCSS,isanapproachforwritingCSSthatencouragesyoutothinkaboutyour
stylesheetsasacollectionofobjects:reusable,repeatablesnippetsthatcanbeusedindependentlythroughout
awebsite.
NicoleSullivansOOCSSwiki
SmashingMagazinesIntroductiontoOOCSS
BEM,orBlockElementModifier,isanamingconventionforclassesinHTMLandCSS.Itwasoriginally
developedbyYandexwithlargecodebasesandscalabilityinmind,andcanserveasasolidsetofguidelinesfor
implementingOOCSS.
CSSTricksBEM101
HarryRobertsintroductiontoBEM
WerecommendavariantofBEMwithPascalCasedblocks,whichworksparticularlywellwhencombinedwith
components(e.g.React).Underscoresanddashesarestillusedformodifiersandchildren.
Example
//ListingCard.jsx
functionListingCard(){
return(
<articleclass="ListingCardListingCardfeatured">
<h1class="ListingCard__title">Adorable2BRinthesunnyMission</h1>
<divclass="ListingCard__content">
<p>Vestibulumidligulaportafeliseuismodsemper.</p>
</div>
</article>
);
/*ListingCard.css*/
.ListingCard{}
.ListingCardfeatured{}
.ListingCard__title{}
.ListingCard__content{}
.ListingCard istheblockandrepresentsthehigherlevelcomponent
composetheblockasawhole.
.ListingCardfeatured isamodifierandrepresentsadifferentstateorvariationonthe
.ListingCard block.
IDselectors
WhileitispossibletoselectelementsbyIDinCSS,itshouldgenerallybeconsideredanantipattern.ID
selectorsintroduceanunnecessarilyhighlevelofspecificitytoyourruledeclarations,andtheyarenotreusable.
Formoreonthissubject,readCSSWizardrysarticleondealingwithspecificity.
JavaScripthooks
AvoidbindingtothesameclassinbothyourCSSandJavaScript.Conflatingthetwooftenleadsto,ata
minimum,timewastedduringrefactoringwhenadevelopermustcrossreferenceeachclasstheyarechanging,
andatitsworst,developersbeingafraidtomakechangesforfearofbreakingfunctionality.
WerecommendcreatingJavaScriptspecificclassestobindto,prefixedwith .js :
<buttonclass="btnbtnprimaryjsrequesttobook">RequesttoBook</button>
Border
Use insteadof none tospecifythatastylehasnoborder.
Bad
.foo{
border:none;
}
Good
.foo{
border:0;
}
Sass
Syntax
1.Propertydeclarations
.btngreen{
background:green;
fontweight:bold;
//...
2. @include declarations
.btngreen{
background:green;
fontweight:bold;
@includetransition(background.sease);
//...
}
3.Nestedselectors
Nestedselectors,ifnecessary,golast,andnothinggoesafterthem.Addwhitespacebetweenyourrule
declarationsandnestedselectors,aswellasbetweenadjacentnestedselectors.Applythesame
guidelinesasabovetoyournestedselectors.
.btn{
background:green;
fontweight:bold;
@includetransition(background.sease);
.icon{
marginright:px;
}
}
Variables
Preferdashcasedvariablenames(e.g. myvariable )overcamelCasedorsnake_casedvariablenames.Itis
acceptabletoprefixvariablenamesthatareintendedtobeusedonlywithinthesamefilewithanunderscore
(e.g. _myvariable ).
Mixins
MixinsshouldbeusedtoDRYupyourcode,addclarity,orabstractcomplexityinmuchthesamewayaswell
namedfunctions.Mixinsthatacceptnoargumentscanbeusefulforthis,butnotethatifyouarenot
compressingyourpayload(e.g.gzip),thismaycontributetounnecessarycodeduplicationintheresulting
styles.
Extenddirective
@extend shouldbeavoidedbecauseithasunintuitiveandpotentiallydangerousbehavior,especiallywhen
usedwithnestedselectors.Evenextendingtoplevelplaceholderselectorscancauseproblemsiftheorderof
selectorsendsupchanginglater(e.g.iftheyareinotherfilesandtheorderthefilesareloadedshifts).Gzipping
stylesheetsnicelywithmixins.
Nestedselectors
Donotnestselectorsmorethanthreelevelsdeep!
.pagecontainer{
.content{
.profile{
//STOP!
}
}
Whenselectorsbecomethislong,yourelikelywritingCSSthatis:
StronglycoupledtotheHTML(fragile)OR
Overlyspecific(powerful)OR
Notreusable
Again:nevernestIDselectors!
IfyoumustuseanIDselectorinthefirstplace(andyoushouldreallytrynotto),theyshouldneverbenested.If
youfindyourselfdoingthis,youneedtorevisityourmarkup,orfigureoutwhysuchstrongspecificityis
needed.IfyouarewritingwellformedHTMLandCSS,youshouldneverneedtodothis.