Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Reusable Design Patterns in CSS

Reusable Design Patterns in CSS

Optimizing your web site, SMACSS, OOCSS

Rob Riggs

April 21, 2013
Tweet

More Decks by Rob Riggs

Other Decks in Technology

Transcript

  1. Optimize, Optimize • High Performance Web Sites, by Steve Souders

    • Css sprites • Inline Images • Combine stylesheets • External stylesheet • Minify CSS • YSlow Thursday, April 18, 13
  2. The Performance Golden Rule • Reduce the number of components,

    reduce the number of http requests • Only 10% - 20% of the response time is for the HTML, the rest is components Thursday, April 18, 13
  3. Css Sprites • Can save tremendous browser overhead • A

    single image that leverages background position property • How to make spriting less tedious? Thursday, April 18, 13
  4. Background position .squarebutton { background-image: url(‘sprite.gif’); background-repeat: no-repeat; } .squarebutton.red{

    ! background-position:0px 0px; ! border:solid 1px #a30308; } .squarebutton.red:hover{ ! background-position:0px -38px; } .squarebutton.blue{ ! background-position:0px -76px; ! border:solid 1px #035ce0; ! box-shadow:none !important; } .squarebutton.blue:hover{ ! background-position:0px -114px; } .squarebutton.green{ ! background-position:0px -152px; ! border:solid 1px #608d05; } .squarebutton.green:hover{ ! background-position:0px -190px; } Thursday, April 18, 13
  5. How I use images in my CSS • Compass/SCSS/Sprite generator

    • http://apps.ezprints.com/jupiter/css/skins/ default/default-base.css • Base64 embed Thursday, April 18, 13
  6. For the icons that every user is going to see,

    they are generated into a single sprite, and then they are base64-encoded to be rendered inline with the CSS file. It’s a larger hit initially, but the fewer http requests the better. Thursday, April 18, 13
  7. Base-64 inline images • http://www.mobilefish.com/services/base64/ base64.php • Easy maintenance for

    a deployable app • One less http request • However, not good for Retina 2x displays Thursday, April 18, 13
  8. Designing for Retina • Retina graphics are 2x • Keep

    pixel positions even - remove the fuzz • Can have 2 versions - responsive device pixel ratio • Let javascript do it for you - http:// retinajs.com/ Thursday, April 18, 13
  9. Even pixel positions and dimensions • Allows image to resize

    without the fuzz Thursday, April 18, 13
  10. After several iterations between designing the vector in Ilustrator and

    bringing over to PhotoShop to save, I was able to make some improvements. However it still looks like crap in Chrome. Thursday, April 18, 13
  11. Responsive Pixel Ratio Instead of referencing to all your assets

    as separate files, put them in a sprite. 1. Create a 2x version of your asset sprite that is exactly double the size, and has the different assets at exactly double the dimensions inside of the sprite. 2. Gather all the selectors that reference the sprite, and reference them towards the @2xsprite within the media query for high-resolution displays. 3. Make sure you don’t forget to set the background-size property to translate the dimensions of the @2x sprite. Thursday, April 18, 13
  12. span.location { ! background: url(sprite.png) no-repeat 0 0; } span.success

    { ! background: url(sprite.png) no-repeat -100px 0; } a.delete { ! background: url(sprite.png) no-repeat -100px -100px; } .content a.fav-link { ! background: url(sprite.png) no-repeat 0 -100px; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { ! span.location, ! span.success, ! a.delete, ! .content a.fav-link { ! ! /* Reference the @2x Sprite */ ! ! background-image: url([email protected]); ! ! /* Translate the @2x sprite's dimensions back to 1x */ ! ! background-size: 200px 200px; ! } } Thursday, April 18, 13
  13. Sprite Alternatives • SVG - often saved from Illustrator •

    verbose -be sure to optimize the output • font icon libraries • font awesome - http:// fortawesome.github.io/Font-Awesome/ • fontello - http://fontello.com/ Thursday, April 18, 13
  14. Minify CSS • Approximately 20% of all page views are

    done with an empty cache • The lighter the page weight, the better • http://cssminifier.com/ Thursday, April 18, 13
  15. DOM • Document object model • All elements are referenced

    in tree format • XML - XPath • JavaScript - JSON (JavaScript Object Notation) • event.currentTarget.id Thursday, April 18, 13
  16. Optimize DOM elements • Develop from content out • The

    > # of DOM elements, the slower that both CSS and JS performs, as they both ‘traverse the DOM’ • Try some layout utilities to help condense your code - http://yuilibrary.com/ • console.log(document.getElementsByTagName('*').length) Thursday, April 18, 13
  17. Classes or Id’s? • Both must be valid (containing only

    letters, numbers, and a hyphen) • Both must begin with a letter • The name should represent the function and not the appearance • Zen and the Art of Motorcycle Maintenance Thursday, April 18, 13
  18. Function before Form • “Don't base your decisions on romantic

    surface appeal without considering classical underlying form.” - Zen and the Art of Motorcycle Maintenance • Excellent book that uses the motorcycle as a metaphor to discuss philosophical ideas • The hippies are romantics that just ride the motorcycle. The squares are the ones that are concerned with how it functions and tinkering with the machines. • Sounds like designers vs. developers? :-) Thursday, April 18, 13
  19. Good examples • button class=”btn-primary” • img class=”p1” • div

    class=”pod” • section id=”home-products” Thursday, April 18, 13
  20. Id’s are a mixed bag... • Id’s: • must be

    unique (1 per page) • excellent hooks for JavaScript (slight performance eval) • 255x more powerful than a class ( http:// codepen.io/chriscoyier/pen/lzjqh) Thursday, April 18, 13
  21. Classes are modular • Reusable throughout the page • Can

    be stacked • article class=”featurette pull-left selected” • Why would I ever write css like this? • keep it modular Thursday, April 18, 13
  22. How I write them: • Ids : pageHeader, pageFooter (camelcase)

    • Classes: page-wrap, home-store, btn- secondary (hyphenated, all lowercase) Thursday, April 18, 13
  23. SMACSS • Scalable Modular Architecture for CSS (smacss.com) • Jonathan

    Snook - worked for Yahoo, Shopify • Built 100s of websites • Proposes the essential question: • “How do you decide whether to use ID selectors, or class selectors, or any number of selectors that are at your disposal? ” Thursday, April 18, 13
  24. Categories of SMACSS • Base • Layout • Module •

    State • Theme Thursday, April 18, 13
  25. Base rules • Base rules are the defaults. They are

    almost exclusively single element selectors but it could include attribute selectors, pseudo-class selectors, child selectors or sibling selectors. Essentially, a base style says that wherever this element is on the page, it should look like this. body { margin:0;padding:0;} h1 { color: #333; margin: 0; text-decoration: underline; border: solid 1px #000; } a { text-decoration: none; } a:hover { text-decoration: underline;} Thursday, April 18, 13
  26. Base rules • Typography • Links • Image sprites •

    Selectors • Reset Css Thursday, April 18, 13
  27. Layout rules • Divides the page into sections • Holds

    one or more modules together • Put your grids in here • Header, nav, footer Thursday, April 18, 13
  28. Module Rules • The reusable page components: • news feed

    • callout box • store catalog (products) • sidebar content • Ideally you should be able to paste these anywhere in your site and they function as expected - that’s modular code Thursday, April 18, 13
  29. State rules • Short for view state • User response

    state - is it visible? hidden? selected? highlighted? expanded? contracted? error? success? • Site position state - home page? checkout page? Thursday, April 18, 13
  30. Theme rules • Form only, completely separated from function -

    sometimes called a skin • Essential if the site/application is skinned for several different clients/vendors Thursday, April 18, 13
  31. How do browsers evaluate CSS? • ID rules • Class

    rules • Tag/selector rules • Universal rules Thursday, April 18, 13
  32. Key selectors • First the browser looks for key selectors,

    and evaluates from there (looks to find a match) • Browsers read CSS from right to left • img#1 > p.important, div > img, p a • Key selectors would be p, img, a Thursday, April 18, 13
  33. Improve performance • The fewer the rules required to check

    for a given element, the faster that style resolution will be Thursday, April 18, 13
  34. Guidelines • Don’t use universal rules • applies to everything,

    slows it down • Don’t qualify id’s with tags or classes • just use the ID • Dont’ qualify class rules with tag names Thursday, April 18, 13
  35. Bad examples • button#backButton • header#mainHeader nav ul li a.subnav

    • body#aboutPage footer#aboutFooter Thursday, April 18, 13
  36. Good examples • #backButton • even better --> .btn-back •

    nav > .subnav • .footer-about Thursday, April 18, 13
  37. Specificity • Specificity can be very tricky • Style =

    “” : 1000 points • ID = 100 points • class = 10 points • element = 1 point • Star Wars Specificity Guide ( http:// www.stuffandnonsense.co.uk/archives/ Thursday, April 18, 13
  38. Be specific, or succinct • The idea is to be

    specific, I prefer to say succinct ( don’t use Id’s ) • Rather than this: • div.image-assets div.col-one img { float: left;} • just use this: • .image-asset { float: left; } Thursday, April 18, 13
  39. Descendant selectors • AVOID THE DESCENDANT SELECTOR! • According to

    Mozilla, the descendant selector is the most expensive selector in CSS! Use the child selector instead. • Browser read css from right to left, so with descendant selectors the entire document is scanned several times • .three-col .col-one .aside { width: 180px; } Thursday, April 18, 13
  40. Child selectors • Child selectors are preferred as they limit

    the scope of evaluation • element must be a direct child of the parent element (not nested) • .three-col > .col-one > .aside { width: 180px } -- still not very optimized, but better than descendants Thursday, April 18, 13
  41. Use child selectors cautiously • Just because its better than

    descendant selectors, it’s not a panacea. • Especially avoid it with tag/selector rules. This will dramatically increase page rendering time. • Again, just keep it succinct. • One child, level, used sparingly. Avoid more. Thursday, April 18, 13
  42. Rely on inheritance • If a parent element can contain

    the formatting, then don’t apply it to the child • Less evaluations, better performance • ul li { list-style-type: none; } • ul { list-style-type: none; } Thursday, April 18, 13
  43. So how to work with CSS succinctly? • Review SMACSS

    • avoid long descendant chains • use succinct, specific names • OOCSS Thursday, April 18, 13
  44. OOCSS • Object-oriented CSS • Engineered to encourage code reuse

    • Make CSS lighter, more straightforward, and easy to maintain • Especially important across teams of developers Thursday, April 18, 13
  45. Basic principles • DRY - don’t repeat yourself • abstract

    the classes to represent objects (semantic) • use multiple classes to keep repetition low • you can still use Id’s (for Javascript hooks) Thursday, April 18, 13
  46. The Media Object • Developed by Nicole Sullivan • Assumed

    to save several hundred lines of code (for Facebook) • Fits well with SMACSS principles Thursday, April 18, 13