Scalable and Modular CSS FTW!

Post on 18-Oct-2014

2.345 views 3 download

description

If you're working on a large project with a lot of hands in the CSS pot, then your CSS may be doomed to code bloat failure. Scalable and modular CSS architectures and approaches are the new hotness and rightfully so. They provide sanity, predictably and scalability in a potentially crazy coding world. This session will give an overview of some the most popular approaches, including OOCSS, SMACSS, CSS for Grownups, and DRY CSS as well as discussing some general principles for keeping your CSS clean, optimized, and easy to maintain. Presented at FITC Amsterdam 2013

Transcript of Scalable and Modular CSS FTW!

Scalable and Modular CSS FTW!

e Legend of the Birth of MetaCoax

/  *  Denise  R.  Jacobs  Future.  Innova6on.  Technology.  Crea6vity.  Amsterdam,  Netherlands  18  February  2013  */    

I am: @denisejacobs This fine event is: @fitc #FITCAms And I’m telling the tale of: #metacoax

Tweeting tall tales

And tell stories about CSS

I like to make stuff

The Legend of the Birth of MetaCoax chapter 1���Problems in Poësia chapter 2���The Teachings of the Masters chapter 3���Insights and Epiphanies chapter 4���Ousting Selector Evil chapter 5���Triumph!

Chapter 1���Problems in Poësia

http://www.flickr.com/photos/lorenjavier/7324305636/

You know how all stories start…

http://www.flickr.com/photos/drobnikm/525835032/

There was a Kingdom called Poësia

Emperor Eric

http://www.flickr.com/photos/trodel/3801987960/

On the surface, all was fine…

http://www.flickr.com/photos/kathrynvjones/3737219448/

Behind the city’s walls…

http://www.flickr.com/photos/torley/4096277982/

It was a nightmare of dis-organization

http://www.flickr.com/photos/massgovernor/7345462040/

Top architects and designers

http://www.flickr.com/photos/8533266@N04/4457182603/

Who hired builders

http://www.flickr.com/photos/statuelibrtynps/6276757947/

Some believed in mastery…

http://www.flickr.com/photos/anotherjesse/243020629/

Others were not of that mind

http://www.flickr.com/photos/laughingsquid/142398084

Put together with whatever was handy

http://www.flickr.com/photos/cbnsp/6605969807/

Shabby new structures

http://www.flickr.com/photos/dr_john2005/3934871670/

They didn’t start off evil

http://www.flickr.com/photos/dr_john2005/3935163348/

…but they slowly became so over time

Follow suit and try to fit in

http://www.flickr.com/photos/stuckincustoms/6199442617/

Fight by trying to become !important

http://www.flickr.com/photos/bbsc30/168832715/

He sent out his two most trusted aides…

http://www.flickr.com/photos/annegirl/435308460/

They traveled far and wide…

http://www.flickr.com/photos/axsdeny/2607122395/

And found the prophet Marcot

The gospel of Responsive

http://www.flickr.com/photos/44085287@N05/4055807492/

He spoke of a championne

Photo: Denise Jacobs

They traveled south to Mijami…

To find Djieh and Djinn!

Chapter 2���The Teachings of the Masters

http://www.flickr.com/photos/gods-art/6622668251/

They went deep into the canyons

http://www.flickr.com/photos/gods-art/6622669139/

The Dry Wind appeared to them

http://www.slideshare.net/jeremyclarke/dry-css-a-dontrepeatyourself-methodology-for-creating-efficient-unified-and-scalable-stylesheets

DRY CSS

“Don’t Repeat Yourself” Never repeat a style/property definition…ever.

DRY CSS

When looking at making a style declaration for a selector, always have an answer to the question "Why isn’t this part of a group?” Then figure out how to make it one.

DRY CSS: Thinking

Groups define shared properties. Group selectors with shared properties, rather than defining them separately.

While the groups have many selectors, each property/value pair is defined only once.

DRY CSS: Approach

•  Name the groups based on their role in the design •  Use the name as an ID at the top of the list and a

class at the bottom

•  Group selectors that share properties above the properties they share

DRY CSS: How

#LIGHT-WHITE-BACKGROUND,!.translation,!.entry .wp-caption,!#full-article .entry img,!.recent-comment .comment-text,!.roundup h3,!.post-header-sharing,!#post-categories td.label,!#post-archive roundup h3,!.subscription-manager ol,!.light-white-background!{! background-color: #fff;! border-color: #ccc;!}!

For example

http://www.slideshare.net/jeremyclarke/dry-css-a-dontrepeatyourself-methodology-for-creating-efficient-unified-and-scalable-stylesheets

http://www.flickr.com/photos/branditressler/2912153888/

The Ninja

Object Oriented CSS https://github.com/stubbornella/oocss/wiki

OOCSS

Was ruthless

Outcome

CSS bytes/page

19% decrease

HTML bytes/page

44% decrease

•  Large number of floats = bad grid •  Large number of margins = you need a reset css •  Large number of font-size & !important = ���

cascade is not being leveraged

OOCSS: Signs you need it

•  Employ DRY •  Separate structure and presentation

•  Modularize

OOCSS: The Gist

•  Use CSS grids

•  Keep selector chains as short as possible •  Give rules the same weight/strength •  Use <hr> as a page section delimiter •  Style classes rather than elements

OOCSS: Do’s

•  Avoid attaching classes to elements

•  Avoid using IDs as styling hooks, use them for JS hooks and page anchors

•  Avoid the descendent selector

•  Don’t over-semanticize class names •  Avoid classnames that are related to the appearance

of the style

OOCSS: Don’ts

1.  Determine the site-wide “legos” (ie, reusable pieces)

2.  Separate – Container and Content – Structure and Skin – Contour and Background – Objects and Mix-ins

3.  Mix and match container and content objects to achieve high performance design.

4.  Skin for visual difference

OOCSS: The process

OOCSS: The Media Module

http://www.stubbornella.org/content/2010/06/25/the-media-object-saves-hundreds-of-lines-of-code/

<!-- media --> !<div class="media"> !!<img class="fixedMedia" src="myImg.png" /> !!<div class="text"> !!... !!</div> !</div>!

OOCSS: The Media Module

/* ====== media ====== */!.media {margin:10px;}!.media, .bd {overflow:hidden; _overflow:visible; zoom:1;}!.media .img {float:left; margin-right: 10px;}!.media .img img{display:block;}!.media .imgExt{float:right; margin-left: 10px;}!

OOCSS: The Media Module

http://www.flickr.com/photos/stikeymo/308546507/

The Lumberjack

Scalable and Modular Architecture for CSS https://smacss.com/

SMACSS

•  Base •  Layout •  Module •  State •  Theme

SMACSS: Style categories

Selectors should be “shallow” instead of “deep” Strive for the shallowest possible.

SMACSS: Curb your enthusiasm

div#childrens-footer div#col2.column div.bestRight p.bestTitle !

SMACSS: Deep selector

p.bestTitle !

SMACSS: Shallow selector

•  Avoid tag selectors for common elements unless completely predictable. •  Use class names as the right-most (key) selector

•  Use the child selector

SMACSS: Shallow selectors 101

You’re better off adding classes to the elements in question and repeating the class in the HTML than having overly-specific styles.

Instead of being classitis, using multiple classes clarifies intent and increases the semantics of elements in question.

SMACSS: On “classitis”

•  Nav bars •  Carousels •  Dialogs •  Widgets •  Tables •  icons

SMACSS: Module candidates

State changes can be notated by class names like .is-active!.is-collapsed!.btn-pressed!

SMACSS: States

an example module: .example! a callout module: .callout! a callout module with a collapsed state: .callout.is-collapsed!

SMACSS: What’s in a name?

“Constrain, but don’t choke. Consider selector performance, but don’t waste too much time on it.”

SMACSS: Words of Wisdom

http://www.flickr.com/photos/31363949@N02/6958447097/

The Brit

https://speakerdeck.com/u/andyhume/p/css-for-grown-ups-maturing-best-practises http://schedule.sxsw.com/2012/events/event_IAP9410 (audio)

CSS For Grown Ups

http://www.flickr.com/photos/djrue/4835062638/

He lived his own nightmare

Don’t style pages, style modules. Have a style module library that you can reuse.

CSS For Grown Ups

Think of your styles as being in layers: •  document – from HTML code, element selectors •  base styles •  module styles •  layout styles

CSS For Grown Ups

Easy determination: A tag as part of the selector = a document style If you create a class for it, you release it from the tag and make it a module style.

CSS For Grown Ups

…make modules variations based on IDs, base them on classes instead #sidebar .promo-box = bad

.promo-box { ... } = okay! .promo-box-light { ... } = better!

CSS For Grown Ups: Don’t

.promo-box! Related/sub-styles: module’s name extended with two dashes .promo-box--eco! javascript class prefixed with js: .js-login!

CSS For Grown Ups: Modules

.h-headline!.h-subheadline!.h-byline!.h-promo!

CSS For Grown Ups: Typography

“Surgical layout helpers” which are things like paddings, margins, and gutters as separate classes. .margin-top {margin-top: 1em;}!

CSS For Grown Ups: Helpers

Chapter 3���Insights and Epiphanies

http://www.flickr.com/photos/s4xton/2425718415/

The Masters all speak the same truths

•  Ids? Not so much. •  Classes? Aww yeah! •  With selectors, less is more •  Get your module on •  Naming conventions? !Important

Their teachings

•  Structure and Inform

•  Reduce •  Recycle and Reuse

Can be simplified to this:

http://www.flickr.com/photos/trvance/3138749670/

Structure and Inform

•  Utilize a naming convention to establish structure and meaning

•  Categorize styles in the document or into multiple documents

•  Employ grids for consistent page structure

Structure and Inform

Photo: Denise Jacoba

Reduce

•  Eliminate inline styles •  Write the shortest chain of elements possible in

selectors

•  Drop elements: as qualifiers and selectors •  Choose classes over ids

Reduce

http://www.flickr.com/photos/epsos/5575089139/

Recycle & Reuse

•  Leverage the cascade better to cut down on redundant style declarations •  Modularize page components to reuse throughout

site

•  Extend modules through subclassing

Recycle & Reuse

http://www.flickr.com/photos/karent/3673326282/

They figured out the key!

http://www.flickr.com/photos/mdave/2878687949/

What do you do when you build?

http://www.flickr.com/photos/chriscoyier/5269340772/

Exactly!

measure twice, cut once css à

mtco css à meta coa css à MetaCoax!

What should we call it? Hmmm…

{ Measure twice: cut once; }

And thus, MetaCoax was born!

http://www.flickr.com/photos/trodel/3801987960/

Djiejh and Djinn went to Poësia…

Chapter 4���Ousting Selector Evil

.flickr.com/photos/boklm/486646798/

Institute change in 3 phases

•  Optimize selectors

•  Reduce the redundant

(1) Initial phase

•  Eliminate qualifier selectors [oocss]

•  Eliminate the middleman •  Have the shortest chain possible [oocss, smacss]

Optimize Selectors

Qualified selectors

div#!

1259 div.!

836

Selectors like div#widget-nav div#widget-nav-slider ul li div.name span! Could easily be simplified into

#widget-nav-slider .name span! with the exact same outcome.

Eliminate qualifier selectors

If you must use a descendent selector, then eliminate all unnecessary elements in it: .widget li a! would become

.widget a!

Eliminate the middleman

For example, instead of #toc > LI > A! it’s better to create a class, such as .toc-anchor!

Have the shortest chain possible

•  Leverage the cascade by relying on inheritance [oocss]

•  Review, revise and reduce !important ���[oocss, smacss]

Reduce the Redundant

color!font-family !font-size !!font-style!font-variant !!font-weight !!font!line-height !!list-style-image !!list-style-position !!list-style-type !!list-style!text-align!text-indent !!text-transform!visibility!white-space!word-spacing!

Leverage the cascade with inheritance

Not using the cascade

font!

100 font-size!

112

If there are a lot of styles that are !important then…

Review, revise and reduce !important

UR DOIN’ IT WRONG

!important!

126

For example…

•  Clear the cruft

•  Create preliminary portable styles [cfgu]

•  Begin instituting modules based on design patterns [oocss, smacss, cfgu]

•  Institute a Grid [oocss]

(2) Intermediate phase

•  Eliminate inline styles & decrease use of <span> •  Eliminate styles that rely on qualifiers high in the

DOM [oocss]

•  Use classnames as key selector [smacss] •  Create preliminary portable styles [cfgu]

Clear the cruft

body.video div#lowercontent div.children.videoitem.hover a.title { !background: #bc5b29; !color: #fff !important; !text-decoration: none; !}!

Eliminate styles that rely on qualifiers high in the DOM

body#!

936

Too high in the DOM

•  Typographic classes for headings, etc.[cfgu] •  Surgical layout helpers [cfgu]

Create preliminary portable styles

Is surgery necessary?

margin-top!

189 margin-bottom!

112

•  Use CSS3 box-sizing •  Make the grid and images fluid

Institute a Grid

Bad grid

width!

327 margin!

738

.l-col-1-1 {float:none;}!

.l-col-1-2 {width:50%; *width:43%; }!

.l-col-1-3 {width:33.33333%; *width:32.33333%;}!

.l-col-2-3 {width:66.66666%; *width:65.66666%;}!

.l-col-1-4 {width:25%; *width:23%; }!

.l-col-3-4 {width:75%; *width:72%;}!

.l-col-1-5 {width:20%; *width:19%;}!

.l-col-2-5 {width:40%; *width:39%;}!

.l-col-3-5 {width:60%; *width:59%;}!

.l-col-4-5 {width:80%; *width:79%;}!

.l-col-1-6 {width:16.6%; *width:15.6%;}!

Good grid

img {!max-width: 100%;!height: auto;!}!

Make the grid and images fluid

•  Continue modularizing page elements ���[ocss, smacss, cfgu]

•  Continue cleaning-up selectors and styles •  Separate CSS files by category [smacss]

(3) Advanced phase

Chapter 5���Triumph!

http://www.flickr.com/photos/joebehr/6349047969/

Structure

http://i31.photobucket.com/albums/c351/Rasey07/twins.jpg

Inbred selectors banished

http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Ended the Specificity Wars

http://www.flickr.com/photos/digitalfrance/98314057/

Ready for a responsive future

http://www.flickr.com/photos/torley/2761300969/

New best practices

http://necolas.github.com/normalize.css/

Reset with Normalize.css

Still using this? <div class="clear"></div>!…!.clear { clear: both; }!

Use a better Clearfix

/* For modern browsers */!.cf:before, .cf:after { ! content:""; !display: table;!} !!.cf:after { clear: both;} !!/* For IE 6/7 (trigger hasLayout) */!.cf { *zoom:1; } !

The New Clearfix

Seriously? !<div class="divider"></div>!…!div.divider {!border-top: 1px solid #ABAA9A;!clear: both;!}!

And a better Divider

<hr> !

The Ninja says

.hide-text {!text-indent: 100%;!white-space: nowrap;!overflow: hidden;!}!

…And Image replacement

Instead of this: <li class="favorite">!<span class="icon favorite"></span>!<span id="favorite-poem-insert-point" class="favorite"></span>!</li>!

Use an icon element

Do this: <p><i class="icon icon-comment"></i>23 comments</p>!...!.icon {background-image: url( sprites.png ); }!!.icon-comments {background-position: 0 -30px; } !

Use an icon element

http://www.flickr.com/photos/meggers/2378288736/

Share the Love

“Even the cleanest code gets ruined by the first non-expert to touch it.” - Nicole Sullivan, ���The Cascade, Grids, Headings, and Selectors from an OOCSS Perspective

Just revamping the code isn’t enough…

http://www.flickr.com/photos/littlemad/5729783584/

Website styleguide

1.  Determine the unique elements and components that will be in the styleguide. Also notate the main colors for text, header, links, and buttons.

2.  Start styling the core elements of the pages: headings, links, tables, blockquotes, unordered and ordered lists, and forms.

3.  Style the components that override the base styles, such as search boxes, breadcrumb navigation, themed buttons, and variations in modules. Include interaction styles: hover, focus, active states.

Styleguide Creation Process

4.  Add layout last and put the components into place. Each layout could be presented as a separate document.

5.  Document your coding process: naming conventions and the thinking behind decisions of grouping, classifying components, etc.

Styleguide creation process

http://www.flickr.com/photos/lecercle/514344657/

So everyone can access the treasures

With the knowledge of The Masters

http://www.flickr.com/photos/clspeace/2143292403/

The code has been improved!

Srsly!

Start!

7500 Finish!

2250

http://www.flickr.com/photos/drobnikm/525835032/

And made Poësia…

http://www.flickr.com/photos/sonialuna/2942020058/

(You know how I’m going to end this)

Character list and Resources

http://www.flickr.com/photos/localcelebrity/7907876246/

The Marcot

…is Ethan Marcotte, the creator and author of Responsive Web Design (RWD) http://ethanmarcotte.com/ twitter.com/beep

The Dry Wind

…is Jeremy Clarke, the developer of DRY CSS. http://simianuprising.com/ twitter.com/jeremyclarke

http://www.flickr.com/photos/localcelebrity/6025912453/

The Ninja

…is Nicole Sullivan, the creatrice of Object Oriented CSS (OOCSS) http://www.stubbornella.org/ twitter.com/stubbornella

http://www.flickr.com/photos/splat/3742596419/

The Lumberjack

…is Jonathan Snook, the creator and author of Scalable and Modular CSS (SMACSS) http://snook.ca/ & http://smacss.com twitter.com/snookca

http://www.flickr.com/photos/angryamoeba/4674320039/

The Brit

…is Andy Hume, the creator of CSS for Grown Ups (I like to shorten this to CFGU). http://andyhume.net twitter.com/

Djinn

…is Jennifer Dixon, front-end developer extraordinaire http://jdcoding.com twitter.com/jenniration

Illustrations by

Lorenzo Grandi LorenzoGrandi.it

My books

The CSS Detective Guide CSSDetectiveGuide.com���twitter.com/cssdetective

InterAct With ���Web Standards:��� InterActWithWebStandards.com���

twitter.com/waspinteract

Smashing Books #3 &���#3 1/3 SmashingBook.com My chapter: “Storytelling in Webdesign”

And I am…

DeniseJacobs.com denise@denisejacobs.com twitter.com/denisejacobs

Now I really mean it!

http://www.flickr.com/photos/theredproject/3302110152/

Thank You!