CSS Master

(Primo) #1

Hereareexamplesofwhatnottodo:.red-text,.blue-button,.border-4px,
.margin10px.What’swrongwiththese?Theyaretootightlycoupledtotheexisting
designchoices.Usingclass="red-text"tomarkupanerrormessagedoeswork.
Butwhathappensifthedesignchangesanderrormessagesbecomeblacktextinside
orangeboxes?Nowyourclassnameisinaccurate,makingittougherforyouand
yourcolleaguestounderstandwhat’shappeninginthecode.


Abetterchoiceinthiscaseistouseaclassnamesuchas.alert,.error,or.mes-
sage-error.Thesenamesindicatehowtheclassshouldbeusedandthekindof
content(errormessages)thattheyaffect.Forclassnamesthatdefinepagelayout,
addaprefixsuchaslayout-,grid-,col-,orsimplyl-toindicateataglancewhat
itistheydo.ThesectiononBEMmethodologylaterondescribesaprocessforthis.


Avoid Tying CSS Closely to Markup


You’veprobablyusedchildordescendantselectorsinyourcode.Childselectors
followthepatternE > FwhereFisanelement,andEisitsimmediateparent.For
example,article > h1affectstheh1elementin

Advanced
CSS

,butnottheh1elementin

Advanced
CSS

.Adescendantselector,ontheotherhand,follows
thepatternE FwhereFisanelement,andEisanancestor.Touseourprevious
example,article h1selectstheh1elementinbothcases.


Neitherchildnordescendantselectorsareinherentlybad.Infact,theyworkwell
tolimitthescopeofCSSrules.Butthey’refarfromideal,however,becausemarkup
occasionallychanges.


Raiseyourhandifyou’veeverexperiencedthefollowing.You’vedevelopedsome
templatesforaclientandyourCSSuseschildanddescendantselectorsinseveral
places.Mostofthosechildrenanddescendantsarealsoelementselectors,soselect-
orssuchas.promo > h2and.media h3arealloveryourcode.Yourclientalso
hiredanSEOconsultant,whoreviewedyourmarkupandsuggestedyouchange
yourh2andh3elementstoh1andh2elements.Theproblemisthatwealsohave
tochangeourCSS.


Onceagain,classselectorsrevealtheiradvantage.Using.promo > .headlineor
.media .title(ormoresimply.promo-headlineand.media-title)letsuschange
ourmarkupwithouthavingtochangeourCSS.


CSS Architecture and Organization 83

Free download pdf