CSS - OOCSS, SMACSS and more

47,927 views
40,043 views

Published on

An introduction to the changing world of CSS. Slides from Brisbane Web Designer Meetup 13 March 2013.

Published in: Technology
12 Comments
179 Likes
Statistics
Notes
  • More than 5000 IT Certified ( SAP,Oracle,Mainframe,Microsoft and IBM Technologies etc...)Consultants registered. Register for IT courses at http://www.todaycourses.com Most of our companies will help you in processing H1B Visa, Work Permit and Job Placements
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Very well done Russ! I especially liked the way you coin your own terms like 'location agnostic' and replace Nicole's 'media box' with just 'box'. I'm going to be sending our jr. devs to have a look at this for sure!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Very nice slides ;)
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • The problem with your BFC is that you can no longer have drop down menus within that context that overflow the box. Why depend on overflow:hidden; instead of display:block or inline-block??
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • I loved this. Positioning, Box-Model, Background, Text... but I haven't decided where I think CSS3 animations should go yet. In any case, this slideshow definitely got me to thinking. Any thoughts on BEM?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
47,927
On SlideShare
0
From Embeds
0
Number of Embeds
726
Actions
Shares
0
Downloads
643
Comments
12
Likes
179
Embeds 0
No embeds

No notes for slide

CSS - OOCSS, SMACSS and more

  1. CSSoocss, smacss & more...
  2. what’s wro ng with CSS
  3. “CSS is simple... It’s simple tounderstand. But CSS is notsimple to use or maintain. ” http://chriseppstein.github.com/blog/2009/09/20/why-stylesheet-abstraction-matters/
  4. IssuesIf you’ve ever worked on amedium to large website, youhave probably come across arange of issues with CSS.
  5. RepetitionLots of floats, font-sizereferences, heading levelsrepeated...
  6. UnmanageableIt may have started out well, but ithas become a mess?
  7. Weight warYou need to add some CSS - soyou have to start adding toselectors in order to win.
  8. CouplingYour CSS is specifically tied toHTML or location...
  9. CSS sucks!Developers have been telling usfor years that “CSS sucks”. Weall know it’s time for our CSSpractices to evolve.
  10. New stuff!Luckily, there are a wide range ofexciting new developments toexplore.
  11. Biases aside...Before we start... put aside anybiases. At least until after thepresentation, when you can ripinto me :)
  12. ss oc oriented csso object
  13. What is OOCSS?
  14. In 2009, NicoleSullivan introduced anew way of lookingat CSS. She definedthis as ObjectOriented CSS(OOCSS).
  15. StatisticsAfter optimising Facebook’s CSS,she discovered some amazingstatistics... about how we reapplyCSS properties throughout ourstyle sheets.
  16. Facebook:Facebook blue 261 Unique colors 548 colors 6,498 Salesforce: padding 3,668 h1-h6 511
  17. ““We have been doing it allwrong.... Our best practices arekilling us” ” Nicole Sullivan
  18. “The purpose of OOCSS is toencourage code reuse and,ultimately, faster and moreefficient stylesheets that areeasier to add to and maintain. ” http://coding.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/
  19. Looking for patterns - rows
  20. AbstractionOne of the key aims of OOCSSis to abstract as manycomponents of the layout aspossible.
  21. ExampleCan you see any repeating visualpatterns?
  22. RowsThe first layout pattern could bethe rows.
  23. rowrowrowrow
  24. rowrowrowrow
  25. Past practiceIn the past, people may havestyled these rows using a seriesof IDs.
  26. #header#main#news#footer
  27. OOCSS aims1. use a single class so that it canbe reused as needed2. abstract the module down tocore purposes
  28. Core purposesThese rows have two purposes:1. clear each row2. trigger the block formattingcontext.
  29. .row.row.row.row
  30. Re-useThen we can write one simple,but very powerful class that canbe reused anywhere in the layout.
  31. .row {! clear: left; Clears each row! overflow: hidden; Triggers block formatting! zoom: 1; Triggers haslayout in IE5-7! _overflow: visible; IE6 underscore hack}
  32. Different rows
  33. Different rowsDid you notice that two of therows were different? They havedifferent background colours andadditional padding above andbelow.
  34. New names?We could now add some classesbased on the purpose of theserows - such as “news” and“footer”.
  35. .news {! padding: 1em 0;! background-color: blue;!}.footer {! padding: 1em 0;! background-color: pink;!}
  36. AbstractHowever, it would be better toabstract these names further sothat they are more flexible.
  37. .row {! clear: left;! overflow: hidden;! zoom: 1;! _overflow: visible;}.row-alt1 {! padding: 1em 0;! background-color: blue;!}.row-alt2 {! padding: 1em 0;! background-color: pink;!}
  38. <div class="row"></div><div class="row"></div><div class="row row-alt1"></div><div class="row row-alt2"></div>
  39. FurtherIf you wanted, these could beabstracted even further intopadding and backgrounds asseparate concepts.
  40. .row-padding {! padding: 1em 0;}.bg-color1 {! background-color: blue;!}.bg-color2 {! background-color: pink;!}
  41. <div class="row"></div><div class="row"></div><div class="row row-paddingbg-color1"></div><div class="row row-paddingbg-color2"></div>
  42. Up to youIt depends on the site andcircumstances as to how far youthink you need to abstract theseconcepts.
  43. The row module
  44. Primary moduleThe “row” class is our primarymodule. The additional classesare “modifiers” as they modifythe primary class.
  45. ModifiersModifiers should not rewrite anyaspect of the primary module,they only modify or add to theprimary module.
  46. Types of classPrimary module Sub-module Modifier.row-alt1 .row-alt1
  47. Looking for patterns - columns
  48. ColumnsThe second layout pattern couldbe the columns. The wide layoutlooks like it has four columns.
  49. Column 1 Column 2 Column 3 Column 4
  50. PatternsSome of the rows spread acrossall columns. Others spreadacross two or one column.
  51. Column 1 Column 2 Column 3 Column 44 columns2 columns 2 columns2 columns 2 columns1 columns 1 columns 1 columns 1 columns
  52. Framework 1To be safe, we should assume weneed containers for 4, 3, 2 and 1column widths. We can convertthese column options into asimple grid framework.
  53. Wide layout Class names4 column box .w-4col3 column box .w-3col2 column box .w-2col1 column box .w-1col
  54. <div class="row">! <div class="w-4col"></div></div><div class="row">! <div class="w-2col"></div>! <div class="w-2col"></div></div><div class="row row-alt1">! <div class="w-2col"></div>! <div class="w-2col"></div></div><div class="row row-alt2">! <div class="w-1col"></div>! <div class="w-1col"></div>! <div class="w-1col"></div>! <div class="w-1col"></div></div>
  55. NarrowThe same is true of the narrowlayout, except this time it hasonly two overall columns.
  56. Column 1 Column 2
  57. 2 columns1 columns 1 columns1 columns 1 columns1 columns 1 columns
  58. Framework 2We could also create a second,different grid for narrow screen.This would allow us to controlwhether columns sat beside eachother or below at a narrowerscreen size.
  59. Narrow layout Class names2 column box .n-2col1 column box .n-2col
  60. <div class="row">! <div class="w-4col"></div></div><div class="row">! <div class="w-2col n-2col"></div>! <div class="w-2col n-2col"></div></div><div class="row row-alt1">! <div class="w-2col n-2col"></div>! <div class="w-2col n-2col"></div></div><div class="row row-alt2">! <div class="w-1col n-2col"></div>! <div class="w-1col n-2col"></div>! <div class="w-1col n-2col"></div>! <div class="w-1col n-2col"></div></div>
  61. Control!With these two simple grids, wecan control complicated layouts -both wide and narrow.
  62. Looking for patterns - boxes
  63. Boxes?You may have noticed that therewere also a series of smallerboxes, each with an image to theleft or right.
  64. Core purpose1. contain content2. feature object to left or right3. content beside feature object4. margin below
  65. Adaptable boxWe need to create an adaptable box:- could be placed anywhere- any width or height- any feature content- feature content could be left/right- any content inside the body
  66. TargetWe need to be able to target- the overall box- the object (left or right)- the body content within the box- a possible heading (h1-h6)- possibly even the contents itself
  67. box box body This is a heading heading box box feature Lorem ipsum dolor sit amet consect etuer adipi scing elit sed diam nonummy nibh box content euismod tinunt ut laoreet dolore magna aliquam erat volut.
  68. There are a range of possible class we could use here..box { }.box-feature { }.box-feature-alt { }.box-body { }.box-heading { }.box-content { }
  69. WidthDo not give the box a width -allow it to spread to fit the widthof any parent container.
  70. Contain floatsThis box module must contain(and therefore wrap around)either a left or right floatingobject. We can solve this bytriggering the block formattingcontext on the parent.
  71. .box {! overflow: hidden; Triggers block formatting! zoom: 1;! _overflow: visible;! margin-bottom: 1em;}
  72. Location Agnostic The box must work when placed anywhere within the layout. The box must be “location agnostic”.aside .box { }.box { }
  73. Sit besideThe box may contain objects thathave varying widths. We need ourcontent box (“box-body”) to sitbeside these objects, regardlessof their widths.
  74. BFC againWe can solve this by triggeringthe block formatting context onthe “box-body” class.
  75. box-bodyThis is a headingLorem ipsum dolor sit amet consect etueradipi scing elit sed diam nonummy nibheuismod tinunt ut laoreet dolore magnaaliquam erat volut.
  76. .box-body {! overflow: hidden; Triggers block formatting! zoom: 1;! _overflow: visible;}
  77. The box module
  78. Powerful boxWe have just made a verypowerful box. Nicole Sullivanrefers to this box as the “media”element.
  79. .box,.box-body {! overflow: hidden;! zoom: 1;! _overflow: visible;}.box { margin: 0 0 10px; }.box-feature {! float: left;! margin: 0 10px 0 0;}.box-feature-alt {! float: right;! margin: 0 0 0 10px;}
  80. Primary moduleIn this case, the “box” class isour primary module. There are nomodifiers, but there are a range ofsub-modules.
  81. Sub-modulesSub-modules are other classesassociated with the primarymodule. They do not alter or adddirectly to the primary module.
  82. Types of classPrimary module Sub-module Modifier.row-alt1 .row-alt1.box .box-feature .box-body
  83. Moving forward
  84. Semantic classesFor years, we have been taughtto keep our markup clean andonly use “semantic” class names.
  85. Break the rules?OOCSS seems to break both ofthese rules - and in a big way.But have we been thinking about“semantic” class names in thewrong way?
  86. “HTML class names offer nosemantic value to search enginesor screen readers, aside frommicroformats. ” http://www.brettjankord.com/2013/02/09/thoughts-on-semantic-html-class-names-and-maintainability/
  87. “Rather than concerningourselves with creating semanticclass names, I think we should bethinking about creating sensibleclass names. Sensible classnames offer semantics, but they ”also offer flexibility/reusability. http://www.brettjankord.com/2013/02/09/thoughts-on-semantic-html-class-names-and-maintainability/
  88. “If your class is called “blue” andyou want to change it to red, youhave far bigger problems thanclass names to deal with! ” https://speakerdeck.com/andyhume/css-for-grown-ups-maturing-best-practises
  89. Move forwardIn order to move forward,especially on large scale sites, wecannot keep using old practices.
  90. Solution?OOCSS offers front enddevelopers an alternative - lightweight, modular CSS that can bere-used repeatedly across sites.
  91. acss srmtecturecss achi
  92. What is SMACSS?
  93. “SMACSS is more style guide thanrigid framework - an attempt todocument a consistent approachto site development when usingCSS. ” http://alistapart.com/article/frameworksfordesigners
  94. In 2011, JonathanSnook introduced anew way of looking atCSS architecture.He called thisScalable and ModularArchitecture for CSS(SMACSS)
  95. Categorization
  96. CategoriesBase rulesLayout rulesModule (and sub-module) rulesState rulesTheme rules
  97. BaseBase rules are the defaults. Theyare almost exclusively singleelement selectors.
  98. LayoutLayout rules divide the page intosections. Layouts hold one ormore modules together.
  99. ModulesModules are the reusable,modular parts of our design. Theyare the callouts, the sidebarsections, the product lists and soon.
  100. SMACSS allows forprimary modules, modifiersand sub-modules, though theyare labelled slightly differently.
  101. Primary module Sub-module Modifier Sub-component Sub-module.row-alt1 .row-alt1.box .box-feature .box-body
  102. StatesState rules are ways to describehow our modules or layouts willlook when in a particular state. Isit hidden or expanded?
  103. ThemesTheme rules describe how thelayout or modules might look.
  104. Naming Convention
  105. Avoid IDsUse classes rather than IDs forstyling purposes. Classes aremore flexible. Using classes canreduce specificity issues.
  106. MeaningfulClass names should bemeaningful for other authors, sothat other developers canunderstand their purpose.
  107. PatternClass names should followunderstandable patterns.
  108. PrefixesUse “pseudo-namespaces” asprefixes - so that modules,modifiers and sub-modules canbe identified.
  109. Modifiers Possibly use different naming conventions for modifiers, sub-modules and states..example-widget { }.example-widget--modifier { }.example-widget__sub-module { }.example-widget--is-somestate { }
  110. Decouple HTML/CSS
  111. “I’ve noticed that designerstraditionally write CSS that isdeeply tied to the HTML that it isdesigned to style. How do webegin to decouple the two formore flexible development with ”less refactoring? http://coding.smashingmagazine.com/2012/04/20/decoupling-html-from-css/
  112. DecoupleSo how do we “decouple” ourHTML and CSS.1. using additional class names2. using child selectors
  113. ExampleTo see this in action, let’s look atthe “box” example from earlier.What if we wanted to style theheading inside the “box-body”.
  114. This is a heading headingLorem ipsum dolor sit amet consect etueradipi scing elit sed diam nonummy nibheuismod tinunt ut laoreet dolore magnaaliquam erat volut.
  115. Style the h2?We could style this heading usingsomething like this:.box { }.box h2 { }
  116. <div class="box">! <img class="box-feature"! src="dummy-140.png" alt="">! <div class="box-body">! ! <h2>Heading</h2>! ! </p>Lorem ipsum dolor</p>! </div></div>
  117. Problem?The problem is that the CSS is“coupled” with the HTML. Whathappens if there is an <h3>element inside the box?
  118. One solution would be to set allheading levels..box { }.box h1 { }.box h2 { }.box h3 { }.box h4 { }.box h5 { }.box h6 { }
  119. Use a classHowever, the safest way to“uncouple” the CSS and HTMLwould be to use a simple class.
  120. <div class="box">! <img class="box-feature"! src="dummy-140.png" alt="">! <div class="box-body">! ! <h2 class="box-heading">! ! ! Heading</h2>! ! </p>Lorem ipsum dolor</p>! </div></div>
  121. More flexibleNow our HTML and CSS are moreflexible. It doesn’t matter whatheading level is used..box { }.box-heading { }
  122. a closer look at modules
  123. GuidelinesThe following “module” guidelinesapply regardless of whether youare coming from OOCSS orSMACSS.
  124. Rule 1:keep modules simple
  125. “By making your base objects thissimple your choices becomeboolean; you use the object oryou don’t. The object is eitherentirely suitable as a basis, orentirely _un_suitable. ” http://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/
  126. Keep ‘em simpleThe base module should bedefined as simply as possible.This means that they are highlyflexible.
  127. Let’s use an example of our “row” class. What if we added some padding to this rule?.row {! clear: left;! overflow: hidden;! padding: 20px 0;}
  128. But what if we want a row thatdoesn’t have padding? Theproblem is that this rule is nowvery specifically defined. It istherefore not as flexible.
  129. Rule 2:don’t undo styles
  130. “Any CSS that unsets styles (apartfrom in a reset) should startringing alarm bells... Rulesetsshould only ever inherit and addto previous ones, never undo. ” http://csswizardry.com/2012/11/code-smells-in-css/
  131. Don’t undoLeading on from the first rule, youshould avoid writing rules to undoa previous module.
  132. For example, what if you wanted almost all of your headings to have a border-bottom?h2 {! font-size: 1.5em! margin-bottom: 1em;! padding-bottom: 1em;! border-bottom: 1px solid red;}
  133. But in some cases you mightwant a heading without aborder-bottom.
  134. You could write a new rule like this:.no-border {! padding-bottom: 0;! border-bottom: none;}
  135. This is not ideal. It is much betterto write sub-modules that addstyles, rather than write sub-modules to undo styles.
  136. So, a better way might be towrite two rules like this:
  137. /* default style */h2 {! font-size: 1.5em! margin-bottom: 1em;}/* only when border needed */.headline {! padding-bottom: 1em;! border-bottom: 1px solid red;}
  138. Rule 3:extend but don’t modify
  139. Don’t modifyBase modules can be extendedusing sub-modules. However, thebase module itself should neverbe modified.
  140. This is based on the objectoriented programming “open/close principle”.
  141. “Software entities (classes,modules, functions, etc.) shouldbe open for extension, but closedfor modification. ” http://en.wikipedia.org/wiki/Open/closed_principle
  142. If a based module needs to bemodified to suit a specific case, itis probably better to create anew module.
  143. Rule 4:think before adding new modules
  144. Don’t rushIt is always tempting to add amodule based on your need atthe time... as well as based onthe needs of the system.
  145. This often happens after the initialplanning and build has beendone. It’s easy to be tempted by“I’ll just drop this new class inat the bottom of my CSS”.
  146. However, adding poorlystructured new modules, withoutrigorous abstraction, will lead tobloated, hard-to-manage CSS.
  147. icescodingpract
  148. Comment conventions
  149. DocBlockThere is a growing trend to usethe DocBlock as an overallcomment convention. In fact, amovement around this type ofcommenting began over 6 yearsago with the CSSdoc group
  150. “"A DocBlock is an extended C++-style PHP comment that beginswith "/**" and has an "*" at thebeginning of every line.DocBlocks precede the elementthey are documenting... ” http://en.wikipedia.org/wiki/PHPDoc
  151. /** * Short desc * * Long description first sentence starts * and continues on this line for a while * finally concluding here at the end of * this paragraph * * The blank line above denotes a paragraph */
  152. Formatting CSS rules
  153. Single line?In the early days of CSS, a lot ofdevelopers preferred single lineCSS rules as they could easilysee the selectors.
  154. Multi-lineToday, with the complexity ofindividual rules, most developersseem to prefer either themulti-line format, or multi-linewith indenting format.
  155. CSS Tricks rule formatting pollMulti-line Format with Indenting 44%Multi-line Format 28%Single-line Format 11%Single-line Format with Indenting/Tabbing 5%Mostly Single-line Format 5%Single-line Format with Tabbing 4%Other 3% *CSS-tricks poll: http://css-tricks.com/different-ways-to-format-css/
  156. .navigation_rss_icon {! position: absolute;! left: 940px;! bottom: 0px;}#navigation_rss {! position: absolute;! left: 720px;! font-family: Verdana, Arial, Helvetica, sans-serif;! text-transform: uppercase;! color: #897567;! line-height: 2.5em;}#navigation_rss li {! display: inline;}#navigation_rss li a:link, #navigation_rss li a:visited {! color: #fffffe;! text-decoration: none;
  157. .navigation_rss_icon { position: absolute; left: 940px; bottom: 0px;}#navigation_rss { position: absolute; left: 720px; font-family: Verdana, Arial, Helvetica, sans-serif; text-transform: uppercase; color: #897567; line-height: 2.5em;} #navigation_rss li { display: inline; } #navigation_rss li a:link, #navigation_rss li a:visited { color: #fffffe; text-decoration: none;
  158. Declaration order
  159. Alphabet?Similarly, many developers usedto prefer to sort their declarationsalphabetically.
  160. GroupToday, most people prefer togroup their declarations by type.
  161. CSS Tricks declaration formatting pollGrouped by type 45% 45%Random - 39% 39%Alphabet - 14% 14%By line - 2% 2% *CSS-tricks poll: http://css-tricks.com/different-ways-to-format-css/
  162. .selector { /* Positioning */ position: absolute; z-index: 10; top: 0; right: 0; /* Display & Box Model */ display: inline-block; overflow: hidden; box-sizing: border-box; width: 100px; height: 100px; padding: 10px; border: 10px solid #333; margin: 10px; /* Color */ background: #000; color: #fff /* Text */
  163. Of course, many tools and pre-processors take care of this foryou. If your tools do not have thiscapability, take a look at CSSCombhttp://csscomb.com/
  164. get busy!
  165. Russ WeakleyMax DesignSite: maxdesign.com.auTwitter: twitter.com/russmaxdesignSlideshare: slideshare.net/maxdesignLinkedin: linkedin.com/in/russweakley

×