
Ask HN: Anyone have a really smart way to organize css? - katieben
I'd love to see an example of super organized, tight CSS. Do you organize by location (header, footer, body), by function (typography, position data), or both, with multiple instances of the same selector? Wondering how my css stacks up and where I could improve. Thanks! (:
======
simonw
Natalie Downe, my co-founder, has a very neat technique for organising CSS
which she calls a CSS System. She described it in this talk:

<http://lanyrd.com/2008/barcamp-london-5/sg/>

She splits everything in to general styles (basic HTML elements), helper
styles (things like forms, notifications, icons), page structure (header,
footer, layout columns etc), page components (reusable composable classes for
components that occur on different pages in different combinations, such as a
news teaser) and over-rides (special cases for individual pages, rarely used).

She hardly ever uses IDs, preferring classes for almost everything - because
CSS written against classes can be used more than once on a page.

She uses CSSEdit's groups feature to make the CSS easier to navigate - it's
all in one file. <http://macrabbit.com/cssedit/>

View the stylesheets on <http://lanyrd.com/> and follow the link at the top to
the unminified version to see annotated examples.

~~~
dfischer
ID's are useful for unique element styling which will always be a case in a
website. There's certain elements that are absolutely unique.

Goes hand-in-hand with javascript to ease selector targeting.

I never scope ID's either, that's the wrong way to do it. An ID is always
unique so it is top-level.

~~~
simonw
The problem with absolutely unique elements is that, in a complex enough
website (that evolves over time), they often end up not being unique after
all.

I agree about IDs for JavaScript though.

~~~
evanrmurphy
_"I agree about IDs for JavaScript though."_

Would you mind elaborating on the JavaScript point? Is it for convenience with
document.getElementById or something?

Using jQuery, I tend to prefer class selectors the same as in my CSS.

~~~
skbohra123
Jquery class selector is the slowest selector, avoid them as much as possible.
ID selector is the fastest. So, if your application is jquery intense, better
avoid css selectors.

~~~
ricardobeat
in modern querySelector implementations (any real browser), class look-ups are
just as fast as IDs.

------
zefhous
Ideally, I use Sass with Compass (<http://compass-style.org/>). This alone is
a great start to keeping things organized. One of the things I love about Sass
is that it allows partials and variable declarations, which both help
immensely with code organization.

Then, my code is usually organized as follows. Each section can be extracted
to a partial if it gets long enough or if more separation is desired.

    
    
      Framework includes and resets
      Variable declarations — colors, possibly specific widths  
      Universal method declarations
      Standard global tags — headings, p, a, ul, li, etc... 
      Generic form styling, usually in a dedicated partial
      Layout — container, header, content, footer
      Then to specific section styling
    

Since Sass uses indentation, I indent everything in each section within a top
level tag. This really helps visually distinguish each section and gives a
much less uniform look to the stylesheet which makes it a lot more scannable.
If a section uses methods exclusively I'll declare them just above the top-
level section tag.

I'm pretty happy with this approach. It was formed fairly organically but
become more defined as I use it for more projects. It also seems to work well
for both large and small projects, since partials can be used when the code
starts getting long.

~~~
nagash
The biggest problem that I have with Sass is that the file/line references in
your developer tools point at the compiled CSS files, and so you don't have
any real reference to where in your Sass files that style is defined. Any
solution for this?

~~~
robflynn
For me, at least in my rails project using Sass (scss): Development mode also
creates inline comments in the generated CSS which describe where, in the
original scss, the information can be found.

What an awkward sentence. I need sleep.

~~~
lynnwallenstein
Another option if you are using something like rails is in your development
mode just link to the individual CSS files
([http://forrst.com/posts/Rails3_Linking_to_CSS_Differently_De...](http://forrst.com/posts/Rails3_Linking_to_CSS_Differently_Depending_on-
gkN))

------
storborg
I have four core files:

    
    
        reset.css    - I use eric meyer's
        elements.css - Global defaults for things like body,
                       h1, h2, h3, p, a, input, strong. All
                       or almost all selectors in here are
                       just tag names.
        layout.css   - Just sets up the global layout with
                       containers: e.g. header, footer, left
                       column, right column.
        blocks.css   - Reusable chunks.
    

In addition to that, I use a separate file for each "page type". For example,
'article.css', 'index.css', stuff like that. Some larger sites merit
additional files like splitting off 'forms.css', 'tabular.css', etc.

All files get concatenated and minified before serving, obviously.

~~~
AyKarsi
What would you put in chunks.css? Could you maybe provide a brief example?

~~~
kaylarose
I can't speak for the OP, but as I use a similar system I can venture a guess
that some of the following might be worthy of chunk status...

For a website: callouts, user quote styles, tables styles [zebra stripes,
etc.], feature lists, intro paragraph styles, Flash/message styles, common
control styles, etc.

------
peng
At some point, the amount of CSS complexity becomes best handled by a
preprocessor.

Stylus is great: <http://learnboost.github.com/stylus/>

I made a post about it, and personally prefer it to Sass and Less:
<http://nylira.com/stylus-the-revolutionary-successor-to-css/> The hardcore
abbreviation mixins in my post seem to offend some coders. When you work in
CSS and HTML hours every day though, every character saved adds up to a huge
productivity boost.

My current project has 30 directories with 73 partial Sass files, which
compile down to one 320kb file.

As to your question, I organize my partials based on controller and url
structure.

~~~
erikpukinskis
_My current project has 30 directories with 73 partial Sass files, which
compile down to one 320kb file._

Isn't that a lot to download? That's like 2 seconds on average to download
that file in the U.S., and probably in the 10 seconds or higher range for a
lot of folks. I guess if the download is delayed to after some kind of
engagement (sign up, etc) it's not a big deal?

Is 320K of CSS really necessary? (legitimately asking)

~~~
mattdawson
IMHO, it's not.

I'm working on a few relatively complex web apps where the CSS download time
don't come to anywhere near that size. In my world (mobile devices, in
particular) 320k would be totally unacceptable. 100k is about the point where
I start re-evaluating my design.

------
duopixel
After many years doing CSS my best workflow has come to this:

    
    
        reset.css //for resetting browsers
        grid.css //if I'm using a css framework
        global.css //styles that are shared across the site
        section.css //styles that pertain a specific section. The name of the file varies, i.e. "about.css".
    

You need a good code editor that allows you to open files without tabbing or
reaching for the mouse, I use Textmate's Command T to switch fast among my
files.

 _reset.css_ There's a bunch around, I use the one from htmlboilerplate.com,
but there's many good ones available. (Eric Meyer's). You will almost never
touch this file.

 _grid.css_ I only use this occasionally, when I'm working on sites where the
grid is very clear and I take out all the stuff I'm not going to use. I
usually go for a three col version of 960.gs and trim it to about 12 lines of
css. Never touch this.

 _global.css_ Here you put your nav, your footer, you body styles, etc. I
think that separating by colors and typography doesn't make sense, because you
usually change a widget's appearance.

 _section.css_ I count on the body tag having a classname, so I can have body
class="about" and then do...

    
    
        .about section.photo {...}
    

This way you never override your styles accidentally.

 _Miscellaneous_ I avoid the _one declaration per line_ convention when I have
similar styles and I want to be able to read them in a table format, i.e.

    
    
        .available {background-color: #0f0;}
        .taken     {background-color: #00f;}
        .deleted   {background-color: #f00;}
    

I usually start from the most generic to the more specific, but I don't worry
too much about code order because in the end I just do a search and reach it
in no time.

------
tomfakes
Slightly related, but mainly a formatting issue, I format my css files as
such:

    
    
      .foo    { x: y; a: b }
      .bar    { m: n }
      .baz    { background: blah blah url(xyz.png) top left;
                x: y; i: j; }
    

instead of the more commonly seen:

    
    
      .foo {
        x: y;
        a: b;
      }
    
      .bar {
        m: n
      }
    
      .baz { 
        background: blah blah url(xyz.png) top left;
        x: y; 
        i: j; 
      }
    

My format takes up less vertical space in the editor. Sometimes, I can get my
entire CSS file into a single page on the screen, reducing the amount of time
I spend scrolling and searching. I do split lines when they go off the edge of
the space, as seen in the .baz example.

~~~
eam
I prefer the latter. It's more readable IMO. If file size is an issue, I just
use a CSS compressor. Also, it's not too hard in finding selectors, most IDE's
or text editors have a "Find" command to locate a selector. That's my 2 cents.

~~~
tomfakes
This isn't about file size at all, it is about being able to see as much CSS
as possible at one time.

My screen is wide, my editor is wide, my code is fairly wide, but the standard
format for CSS is really narrow. Every time I see the vertical format in my
editor, easily 80% of the window space is completely empty, and otherwise
useless, and 80% of the CSS is not on the screen and I have to page up and
down, or search, to find stuff.

This is a workflow optimization that works for me. It might work for others
too.

~~~
prawn
I do it too and for the same reasons. Just easier to keep your head around if
you can see and scan more of the file at once. I tend to list properties with
the most crucial to layout first so it's easy to find major problems (e.g.,
float, etc).

------
karl11
I'm hoping for some good answers here, because I'd love a better way.

I always put universal elements first (body, img, @font-face, etc.), then I
just organize it top to bottom by page location (i.e. header, content,
sidebar, footer, etc.). I also tab-indent so that elements within another are
indented and "contained" underneath, making it easy for me to move from one
section to the next. I also write the CSS horizontally, only making a new line
for a new element.

I should also note that I'm a n00b :-), so this could be a horrible way to do
it.

~~~
j79
With the exception of the horizontal CSS (personal preference - unless its
compressed, I prefer things on new lines), I like everything you said.

(I actually find the tab-indented elements really interesting and may have to
try it on my next project!)

One thing you didn't mention were comments. I've seen some css files with
great commenting. For instance, comments at the top that act as an index/table
of content for the css file. Very nice!

------
bitsm
I can't recommend Compass/Sass highly enough. A CSS pre-processor will
completely free you to organize your CSS however you want, and more
importantly, it lets you build up a library of common components (forms,
buttons, etc.) that you can easily reuse and adapt for new projects.

Generally, these library files will simply contain mixins (reusable chunks of
code), so they don't output anything directly into your CSS, but allow you to
include the mixins in certain styles. Very useful for adding effects, rounded
corners, etc. on different elements.

Keep in mind however, that mixins can be overused, adding bloat to your code.
CSS does cascade, after all. You should always look to see if you can separate
reusable css rules to include in markup (commonly seen with grid systems). How
you balance out the convenience of keeping your css flexible vs. not littering
your markup with lots of styles really depends on the project, but it's
something to think about.

I have developed one very useful trick while using Sass for managing colors.
Instead of assigning colors directly to an element (very hard to track down
later if a change is necessary), I create color variables named after the
element and attribute in question. Then in my colors.scss file, I build up my
color palette, and after, list all the color variables I created in my
stylesheets, setting their values to the appropriate color from the palette
(with tweaks, if necessary).

    
    
      // in colors.scss ---
    
      // color palette 
      $red: #ff0000;
      
      // assign colors to elements
      $body-background-color: $red;
    
      // in layout.css, for example ---
    
      body {
        background-color: $body-background-color;
      }
    

Since Sass lends itself to lots of files, keeping all my colors and the
elements they are assigned to together in one file makes them much easier to
manage down the road.

~~~
jarin
I do this, but with a slight tweak: instead of naming the colors things like
$red, I _try_ to give them semantic names like $shadow, $highlight, etc. in
case I end up having to pick a completely different color scheme.

~~~
isleyaardvark
Do both. If you pick a completely different color scheme, it's easier to
change $highlight = $red to $highlight = $blue than to remember the hex
values.

------
utunga
Suprised no-one has mentioned Nicole Sullivan's (amongst others) Object
Oriented CSS (OOCSS) project: <https://github.com/stubbornella/oocss/wiki>

She used this approach at Facebook (and Yahoo, I think?) to successfully tidy
up a huge code base of thousands of CSS files down to a more manageable few.

I attended her workshop at Webstock and since then had a chance to put it into
practice on a 'get it up quick' green fields project
(<http://chchneeds.org.nz>). I must say I was really pleasantly surprised at
the way this approach just avoids a lot of the pain points, as a web
developer/coder (ie not an html/css guru) I so often face when just getting
the simplest things to 'work'.

I guess the hardest thing for me to get my head around to was that to make
things more modular you had to let go (a tiny bit) of being so religious about
'semantic html' as a requirement for the HTML, but I think its worth it to get
your CSS a whole lot more modular and 'pluggable' together.

Still a bit more work to do, IMHO, but I'm definitely going to be monitoring
this project closely.

Nicole Sullivan's site: <http://www.stubbornella.org/content/>

~~~
ChrisFulstow
I'm really interested in the OOCSS approach, it's efficient, maintainable and
modular, and although it's not perfectly semantic the trade-off is minimal. I
first discovered it from the Velocity 2009 conference, and Nicole Sullivan's
talk from Web Directions North - <http://goo.gl/yLkby>

------
techiferous
I once tried breaking my css into files according to function (typography.css,
color.css, layout.css). It ended up being a _royal pain_ because when I added
a new HTML element and I went to style it, I ended up having to duplicate the
css selector for that element in three files. I also was constantly switching
among the three files to work with one element's styles. So whatever you do,
_don't_ organize by function. :)

------
mixu
my rules:

1) Layout and widgets only.

I start with a reset, then layout (block positioning), then widgets.
Everything other than layout is a widget. There are no global styles. If there
is one of it, it's an ID. If more, it's a class.

2) No (global) element styles! Ever!

No, not even a p { margin: xyz } or a ul { list-style-type }. Every element
that cannot be referred to by class / id must look exactly like it would after
the reset.

This avoids complex dependency chains where coincidence influences look.
Widgets can be moved from one site to another and you actually have to think
new widgets through rather than relying on the default values.

3) Avoid classes and id's as much as you can.

Have single base element with a simple but descriptive class name, and then
specify the sub-elements.

For example: Instead of “div.content-title” use “#content h1″ (e.g.
div#content with a h1 tag inside it).

Basically, design widgets which consist of one base element, and refer to sub-
elements via longer expressions. Use indentation to separate sub-elements.

My strong preference is to maximize for human readability (=short dependency
chains, descriptive widgets rather than single elements) rather than short
CSS. Cascading within widget-scope is fine, but cascading with global styles
should be avoided. I find that when I follow these rules, I like my CSS a lot
more.

------
dfischer
I leverage SASS and Compass for Ruby heavily.

I utilize mixins heavily so I can modulize all my styling and make sure it's
included in areas that are appropriate. I've learned this is the only way to
handle CSS without styles getting too complicated and accidentally changing
something where you didn't mean to.

Example (create a mixin that has certain styles for forms and then include it
in a body.wizard page) this way I keep my CSS very dry.

General coding guidelines are horizontal. I recently switched to this. I used
to do vertical and indentation but it's very hard to read with big files. I've
found that it's a lot easier to read horizontal CSS.

I alpha all my styles from a-z.

------
carbon8
I also use Sass and Compass. I generally organize the directory roughly like
this for projects without a separate designer:

    
    
        stylesheets
          - ie.sass
          - master.sass
          patials
            - _base.sass
            - _forms.sass
          utilities
            - _custom_mixins.sass
          vendor
            - _facebox.scss
            

The files with leading underscores are partials which are included in the
master.sass. Note that facebox is an scss file. I just dump the CSS in it and
include the partial in master.

The nice thing about sass is that it you can change output format, so you can
just include all the external CSS files as partials and automatically output a
single compressed files with your entire CSS.

When I work with a designer who uses CSS I use a structure like this:

    
    
        stylesheets
          - master.sass
          partials
            - _style.scss
          vendor
            - _facebox.sass
    

In this case, the designer's CSS is dumped in the _style.scss partial, then
included in master.sass. Then in master.sass I include my modifications to the
designer stylesheets. That way I can leave the designer-provided CSS largely
untouched and still have all the flexibility and power of Sass.

------
PelCasandra
Use SASS with partials and mixins and sort them as it's more convenient for
you (probably following the natural flow of descending order of your page).

~~~
bdclimber14
SASS has helped me with organization tremendously. With SASS I keep a
"typography" partial that is the basic text elements (h1, p, etc.) and font-
family variables.

I also have a "colors" partial where I put variables for all my color
definitions, such as $light-blue, $dark-gray, and $background-color.

------
TorbjornLunde
Don't overcomplicate things:

\- Have only one CSS-file, unless your project is _huge_.

\- Never use IDs

\- Avoid reset CSS (espescially if you can ignore IE6/7

\- If you think you need variables (like in SASS), you are probably thinking
about it the wrong way

\- Give classes functional names, not presentational

\- Linebreaks after declaration. (Makes your CSS-file easier to navigate)

\- Remember that you can use you media queries inside your CSS-file

Web designer Jens Meiert has some good articles:

[http://meiert.com/en/blog/20090401/why-css-needs-no-
variable...](http://meiert.com/en/blog/20090401/why-css-needs-no-variables/)

[http://meiert.com/en/blog/20080515/css-organization-and-
effi...](http://meiert.com/en/blog/20080515/css-organization-and-efficiency/)

[http://meiert.com/en/blog/20070321/css-practice-pseudo-
names...](http://meiert.com/en/blog/20070321/css-practice-pseudo-namespaces-
in-complex-projects/)

<http://meiert.com/en/blog/20090527/css-maintenance-issue-1/>

~~~
weallneedheroes
Never use IDs? Why? i'm open to this if you have a good argument but i use IDs
for unique elements only.

~~~
evanrmurphy
The problem is that as a site grows, it's common for things that were once
unique to become multiple.

Also, if you just resolve to always use classes instead of ids, then you can
eliminate the cognitive overhead that comes with every new selector of,
"Should this be a class or an id?".

~~~
perlgeek
How many of your pages have two footers?

I do agree on the cognitive load though.

------
evanrmurphy
Use tables for layout instead of CSS. Then your CSS will be more concise
(essentially reduced to a theme) and less confusing (because CSS layout
properties like float and position tend to cause the most confusion).

 _Edit:_ Rephrased to try and better express the idea.

~~~
michaelsacca
joke?

~~~
evanrmurphy
Not a joke, though I realize it's an unpopular view.

I also had trouble phrasing the idea in a way that didn't sound stupid.

------
mikecomstock
Here's what I do:

\- Almost all CSS goes in 1 big file. One line per selector to keep thinks
clean and easy to find. Styles from external sources (like jQuery UI) go in
separate files.

\- Reset lines go at the top, if you use them, in a / RESET / section.

\- Styles for individual HTML tags are next in the / HTML TAGS / section.

\- Then a / UTILITY CLASSES / section for clearing floats, etc.

\- Next comes site layout. Headers, footers, page width, etc. all go here.
Just the layout though - think the grid. No real content styling yet.

\- Now sections for each piece in the layout. Content styles go here. First a
section for the / HEADER CONTENT /, then a big section for the / PAGE CONTENT
/ (vast majority of styles go here), then the / FOOTER CONTENT / styles.

------
ricardobeat
Use less (<http://lesscss.org/>) - the JS version. Makes your code beautiful:
no repetition, hierarchies, concise. Where I work we've used it for about 9
months now and there is no looking back.

------
bmelton
I haven't used it, as there just hasn't been a project with enough lead time
to experiment with something lately, but I'm fond of the _idea_ of code
generators for CSS, like CleverCSS for Python and Sass for Ruby.

Other than that, the best advice I can offer that I DO follow is that I group
all HTML elements together, all IDs together, and then all classes together.
Within each of those groupings, everything is in alphabetical order.

    
    
      body { foo: bar; }
      form { foo: bar; }
      h1, h2, h3 { foo: bar; }
      input { foo: bar; }
      p { foo: bar; }
    
      #container {}
      #footer {}
      #nav {}
    
      .etc {}
      .even {}
      .odd {}
    

and so forth.

~~~
xdrone
my css is pretty simplistic like this also.

one thing to do is to place class names based on the url with your id's. the
class name can be generated from the request_uri (assuming the html code is in
a view/template/include).

example: <div id="container" class="contact_us">

then if you need tweaks to a specific page, just add #container.contact_us {
foo: bar... }

------
csbartus
Sorry guys,

After reading all comments it seems there is no (universal) solution to write
good HTML/CSS code. Not like in Ruby or Python or other programming languages.

Since this year I'm struggling to create a post / best practices how to code
front-end but the problem is too complex (for me).

The biggest issue is how to mark up HTML to have a DRY (minimal) CSS. And how
to remember easily these mark up rules to be able to maintain anytime in the
future your CSS/HTML.

If you would elaborate your naming / marking up best practices instead of
suggesting frameworks/tools maybe that would help better.

~~~
kaylarose
1\. Separate presentation from layout. For example, all common layout (margin,
padding, display, positioning, floats) go in structure.css and color, border
styles, background, etc. go in presentation.css. It is far more likely that
you will be making presentation changes going forward rather than to your core
layout.

2\. Only use the minimal selectors you need: div#features ul.feature_list
li.feature a{color:red;} could be DRYed up to be .feature_list .feature
a{color:red;} which will be far easier to override later.

3\. Avoid !important at all costs (sometimes you can't, but try).

4\. This is personal taste, but I also usually avoid IDs for styling.

5\. Grid frameworks (Blueprint, etc.) are usually overkill, but syntax
frameworks (LESS CSS, Compass) are fantastic.

It really boils down to experience, and knowing what you DON'T need - most
people add in a ton of extra cruft and end up with hard to extend and debug
spaghetti.

~~~
csbartus
Okay, let's see a simple example.

I have a navigation list which I want to display horizontally as a menu bar.
In plus I want to highlight the current element with jQuery.

How to mark up this list? My immediate answer would be this:

    
    
          <ul id="navigation" class="inline-list">    
             <li><a href="">...</a></li>
          </ul>
    

where .inline-list will transform this list to be displayed horizontally and
#navigation will help to add jQuery on it.

The rule for marking up in this case would be:

    
    
      * use #ID whenever you want to locate an element
      * use .class whenever you want to alter the display of an element from the standard
    
    

Is that simple rule could be extended or made universal? That would be my
question.

~~~
kaylarose
I usually use extra classes instead of IDs to differentiate specific chunks in
cases where the may or may not be multiples in the future (e.g. you want nav
at the top AND bottom of a page).

    
    
          <ul class="main-nav inline-list">    
             <li><a href="">...</a></li>
          </ul>
    

To style/highlight my example the above: //This will not have to be modified
if we want to add more nav instances .main-nav.inline-list li{float:left;}

    
    
        $('.main-nav.inline-list a.selected').highlight();
    
    

To style/highlight your example the above (at top and bottom of page):

    
    
         //Each time you add another instance, you have to add its new id/selector (not very DRY)
         #navigation.inline-list li,
         #navigation_b.inline-list li{float:left;}
    
         $('#navigation.inline-list a.selected, #navigation_b.inline-list a.selected').highlight();
    
    

Again, it's personal style, but I've never found myself saying "boy I wish I
used an ID instead of an adding another class" where many times you regret the
use of ID because when you ultimately need to duplicate that element, you are
effecting the dryness of your CSS and Javascript. Plus, with modern selector
engines the performance of ID vs class based selectors is not really going to
have that big of an impact.

The times I use ID in my markup is more for sub-navigation through the page
rather that styling-specific reasons.

    
    
        <h2 id="chapter_two">Two</h2>
        <a href="#chapter_two">Got to Ch. 2</a>

------
0p9
A good example of some super organized CSS is in the HTML5 Boilerplate by Paul
Irish. Found here:
[https://github.com/paulirish/html5-boilerplate/blob/master/c...](https://github.com/paulirish/html5-boilerplate/blob/master/css/style.css)
I sometimes use multiple instances of the same selector, especially if a
project starts getting very big. I like to separate each function of the site
into it's own block after the footer declarations. It lets me stay organized
during development and ensures that I can keep track of what I'm working on
while I'm working on it. Here's the order I'm currently using, which was
inspired by the above:

    
    
        /* HTML STRUCTURE STYLES */
        body { foo: bar; }
        h1 { foo: bar; }
        a { foo: bar; }
        /* Image Replacement & Hacks */
        .ir { foo: bar; }
        /* Container Styles */
        #header { foo: bar; }
        #main { foo: bar; }
        #footer { foo: bar; }
        .column { foo: bar; }
        .sidebar { foo: bar; }
        .img-cotainer { foo: bar; }
        /* Everything inside of #header */
        .navigation { foo: bar; }
        #header li.nav { foo: bar; }
        /* Everything inside of #main */
        .content { foo: bar; }
        /* Everything inside of #footer */
        .social { foo: bar; }
        #footer li.nav { foo: bar; }
        /* Everything in specific view inside of a container from above */
        .profile { foo: bar; }
        .comments { foo: bar; }
        /* Media Queries */
        @media all and (orientation:portrait {
          * { foo: bar; }
        }
        /* Print Styles using Media Query */
        @media print {
          * { foo: bar; }
        }

------
andyford
Like many of the other commenters, I break the code into reset, global
elements, layout, modules/blocks, and then special overrides if any.

I'll admit it's a personal preference, but as a team consideration I don't
recommend the 'all properties on one line' approach. It's discouraged in other
languages so why do it in CSS?

Definitely check out OOCSS as well as the Natalie Downe talk both posted by in
the comments already.

I can't overstate how highly I recommend Sass/SCSS. It's been mentioned
already as "for Ruby". Yes, you need Ruby installed to use Sass/SCSS but you
do not need to be working on a Ruby project to use it. You can run "sass
--watch (directory name)" from the command line and sass will automatically
compile your .scss (or .sass) files to .css files upon save. Even if you're
scared of the command line I assure you, it's easy! If you're a TextMate user,
there's also a great SCSS bundle here:
<https://github.com/kuroir/SCSS.tmbundle> (it was enough for me to abandon
CSSEdit for good)

One thing that hasn't been discussed in this thread yet is the organization of
properties within a declaration block. It's a good idea to have an approach
and stick with it. Alphabetizing the properties is one approach. I wrote about
my preferred approach a couple years ago here:
[http://fordinteractive.com/2009/02/order-of-the-day-css-
prop...](http://fordinteractive.com/2009/02/order-of-the-day-css-properties/)
(also check out the SitePoint discussion linked in the "Further Reading"
section of the post)

------
chaffneue
I lay my styles out in 1 file and I don't often comment them. Stylesheets
cascade to much to pin them to a specific area of use - it's easier to debug
them by clever naming still - sigh. IE specific files loaded after and only
contain 1 or two tricky IE tweaks. Javascript /Jquery plugins sometimes come
with their own stylesheets, and in those cases I'll leave them where I found
them. For some of the bigger sites with very different looks and feels, I'll
often have a boilerplate (reset to skeleton level) and each page or section
will load in their own stylesheet. Just depends how big the site is.

Order is: * Reset (only for early IE )-<http://developer.yahoo.com/yui/reset/>
I find myself using it less and less

* Global Styles - HTML tags - global font faces

* Clearfix - <http://www.webtoolkit.info/css-clearfix.html>

* Skeleton/Structural Styles - grids/divs/columns

* Headers/footers/persistent styles

* Page specific styles and IDs

* Conditionally load IE Styles if they're required

* load javascript plugin css with the plugin's preferred dir if possible

As for pipelining them, I usually just use a gzipped connection and still
serve them individually, since internal image paths for backgrounds rely on
the CSS path. CSS caches very nicely, so take advantage of it on the HTTP
side.

example:
[http://code.google.com/p/streeme/source/browse/trunk/web/css...](http://code.google.com/p/streeme/source/browse/trunk/web/css/player/desktop/stylesheet.css)

------
findm
I think alot of it depends what it is that you are building. My approach to
would be different if it were building a large scale web app vs a website and
it also depends on the team thats helping to maintain it (ie. if it were to be
maintained by engineers who don't really know or care for css or a team of web
devs)

I always start off with a base which consists of the misc. browser fixes and
hacks + basic typography elements, rough blocking. My philosophy on formatting
really follows what everyone here is saying. I really prefer horizontal lines
and proper tabbing of all the sub elements because its really hard to read
otherwise.

While commenting is really good and I like it, finding the proper balance is
the key. When you're doing fast iteration it gets really tedious and
cumbersome to go back and make sure your comments are in sync.

This is how i arrange my css:
<http://maderogue.com/public/assets/css/base.css>

For bigger project I like to break things down by specific functions & models.
(ie. tables, buttons, sorting controls, etc.)

i really like the way jquery ui themes are done.

------
codejoust
I've really enjoyed SASS/SCSS optionally with Compass. It lets you compile the
stylesheets while still keeping the source files separate and organized. I've
also seen the approach with one big file for the application with commented
sections, however, the drawback to that approach is using a version control
system with multiple editors on a large file (merge conflicts, etc).

------
trevelyan
On an MVC site, I organize by controller. There's one general file for generic
cross-site stuff (header/footer, etc.), supplemented by another CSS file that
shares the markup for all controller-specific pages.

This gives a max of two css files per page. For the landing page I compress
the generic file along with the controller-specific css file for the default
page into a single file. This speeds up the loading process while preventing
too much bloat. Since the other pages are usually hit after the landing page
they require only a single extra download. Any reset code can be included in
there as well, although maintained as a separate file.

I doubt this approach is ideal when it comes to organizing things, but it's
fairly fast when it comes to development. I design by including css in
style="" and then refactoring the markup into classes once the design is
complete. Saves a lot of back and forth while getting things lined up.

~~~
jkjeldgaard
I also organize styles by controller/action in my Rails projects. This trick
from "The Rails 3 Way" is great for assigning the correct classes to the page:

Using Haml:

    
    
      %body(class="#{controller.controller_name} #{controller.action_name}")
    

Using Erb:

    
    
      <body class ='<%= "#{controller.controller_name} #{controller.action_name}"%>'>

------
kj12345
For me the biggest goal is fewer lines to organize in the first place rather
than any particular scheme for grouping. What I do is:

1) Use as few separate stylesheets site-wide as possible so any contradicting
or repetitive rules will be obvious.

2) Use one line per rule so I can scan the selectors quickly, then scroll
horizontally if necessary

3) I prefer complex comma-separated selectors which set one or two properties
to simple selectors which set many properties. Grouping in this way gets me
closer to having constants, e.g. a specific hex color won't be rewritten again
and again, it will just follow a complex selector list.

4) Once a selector works, I try to make it more general, e.g. "div.info {
font-size: 12px }" can probably just be ".info { font-size: 12px }". More
general rules will apply in more cases, so fewer overall rules will be
necessary.

~~~
0p9
_2) Use one line per rule so I can scan the selectors quickly, then scroll
horizontally if necessary_

I'm going to finally start turning off text wrap. You've opened my eyes to
this. Thanks for sharing.

------
Andaith
The system I came up with is A table of contents that makes it easy to jump to
specific styles.

First the global styles, then different things like Header, Navigation, Main
Content, Right-hand-side-doodad, Widgets, Footer, etc.

Then create a Table of contents at the top and give each section a unique
identifier, FEDCBA-Head, FEDCBA-Nav, etc. Go down to each group and put in a
comment saying "Start of Navigation CSS <FEDCBA-Nav>".

Now you can look in the table of contents and do a quick file search on the
unique identifier, and be taken right to the CSS you're looking for.

I generally make the table of contents a lot more detailed, and it has an
upkeep cost, but it's well worth it when the CSS file gets big.

------
stalemath
I usually include comments where necessary before a section, so in a file
named global.css, I may have:

/* header _/ .header { margin: 0 auto; padding: 0; width: 800px; }

/_ body _/ .body { margin: 0 auto; padding: 10px; width: 800px; background-
color: #fff; }

/_ footer */ .footer { margin: 0 auto; padding: 10px; background-color: #EEE;
border-top: 1px solid #BBB; }

(this is just an example, assume the classes are for div's)

If I have multiple CSS files, I may just call one (style.css) in the <head> of
HTML document. Then within the style.css, I can just make a list of the
documents using @import.

((by the way, this didn't come out the way I expected on here))

------
fleitz
Start by using sass reset.sass 960gs.sass default.sass In default @include
reset and 960gs (sass compiles it all into one css file)

Then use a per page sass file that references default.sass

If you want something pre-built that does all this use compass.

------
phenomenia
I write general styles like definitions for *, a, p, ul etc first and after
that I put everithing in DOM order when possible. Starting at the startpage of
the website/project.

Within the selectordefinitions I write general definitions like width, heigt,
displaytype and position (top/left.. margin, padding) first. Then
contentspecific definitions like fontdefinitions. At the end I write border
and background definitions.

That way it's an ease to see if an element hast a specific definitions,
because I know if I'm looking for the width and the first definition is not
the with then there is no width set for this element.

------
phenomenia
I write general styles like definitions for *, a, p, ul etc first and after
that I put everything in DOM order if possible. Starting at the startpage of
the website/project.

Within the selectordefinitions I write general definitions like width, heigt,
display-type and position (top/left.. margin, padding) first. Then
contentspecific definitions like font definitions. At the end I write border
and background definitions.

That way it's an ease to see if an element hast a specific definitions,
because I know if I'm looking for the width and the first definition is not
the with then there is no width set for this element.

------
mattberg
Ever since using Drupal's Zen theme I have preferred their basic setup for
grouping CSS files. Here is a rough example:

html-reset.css layout-fixed.css page-backgrounds.css messages.css pages.css
blocks.css navigation.css comments.css forms.css fields.css print.css ie.css
ie6.css

Drupal's CSS optimization, once turned on, will roll all of these up for you
automatically, so if you aren't using Drupal you will need some sort of build
system to combine and minimize everything. But I think this is a good start.

On a side note, I really like the method the Zen theme uses for CSS columns.
Worth checking that out as well.

------
STHayden
To be honest. With firebug's ability to tell me what line and css files the
style on an element is coming from I don't find spending a lot of time on
organization to have a ton of benefit.

~~~
j79
While I love Firebug, I'd have to counter that organization with CSS is
actually quite important (and does have its benefits!)

This is especially true when you're working either in a team environment or on
a large site. The very nature of CSS (and how things cascade down) can become
a nightmare when organization isn't taken into account from the start.

~~~
steverenz
I agree completely, especially on a web app that is constantly growing. 2 on-
the-job things that help me the most are:

1\. Using the 960 grid system (or your preferred grid flavor) 2\. Grouping by
the following:

Body Typography Forms (Other global stuff like links and buttons) /* Layout
Element 1 _/ ID1 {} ID2 {} class1 {} class2 {} /_ Layout Element 2 */ ID3 {}
ID4 {} class3 {} class4 {}

I also write my styles on one line, but that's just personal preference. I
find it easier to scan down for the selector, then across for the property I
want. I definitely don't do it for aesthetics or file size ;)

------
wordchute
I typically generate css with php, usually in the header but sometimes in a
linked file. Using this method I can easily alter site wide color or fonts,
etc or feed the style atrributes from a database. This method also allows me
to create blocks of css for different page elements and include them as needed
- forms, menus, etc - or dynamically include definitions when conditions are
met. This offers a lot of flexibility in terms of organizing and making
changes to the css.

------
marcuswestin
I tend to build all my DOM in object oriented javascript, and always give the
root element of a UI component the same class name as the name of the
JavaScript class. See eg
[https://github.com/marcuswestin/Focus/blob/master/js/ui/pane...](https://github.com/marcuswestin/Focus/blob/master/js/ui/panels/LeftPanel.js).
The CSS selectors then mirror the structure of thr JavaScript files as well as
the hierarchy of the resulting UI.

------
halles
I use 4 stylesheets:

\- reset (duh) \- layout (structural stuff) \- typography (general typegraphic
styles) \- styles (stuff gets prettier than the already are).

As for the grouping o selectors, i try not to reuse much code so cascading
will not mess stuff up, i'd rather make big css than fragile css. I also try
to group code on a per section basis… just remember i do have a typography
stylesheet which makes most of the stuff readable and pretty before the glitz
rolls in.

------
dools
My colleague @camslizzle just put out <http://stacklayout.com/> \- it's pretty
new but it has a lot of promise I think and has received some favourable
comments around twitter and here on reddit:
[http://www.reddit.com/r/web_design/comments/g3p9d/introducin...](http://www.reddit.com/r/web_design/comments/g3p9d/introducing_stacklayout_a_flexible_width/)

------
nvictor
i saw one guy's css once it it looks like:

    
    
      .wrapper { ... }
          .sidebar { ... }
          .content { ... }
    

the indentation was well done.

~~~
datashaman
We had a GUI 'designer' who did the exact same thing to our whole site. Spent
ages trying to get stuff to work... :)

------
bdclimber14
The best suggestion I can give is to break up your CSS into multiple files. If
you have a "projects" page, make a "projects" CSS file for style definitions
specific to that page. I keep the overall layout elements together. I
typically also have a "forms" CSS file just for buttons, form layouts, and
inputs.

Then @import everything in screen.css.

------
selvakarthi
Organizing the CSS is not a big matter, giving the correct name to the class
and id will lead smart way to organize

------
7oot
I use a single file for each type of media (screen, print ...). Each file has
general styles first (HTML tags), IDs of layout boxes, classes to fine-tune
formatting, and overrides at the bottom (if needed). I like to keep spacing
for readability (maybe minify the files when I'm finished).

------
andraganescu
<http://andreidraganescu.info/blog/1>

I use this system for about 4 years and am still delighted on how easy it
comes to me. In brief:

\- Split up your style sheet according to rule types.

\- There are three main rule types that help when split: grid, decorations and
fonts.

------
evanrmurphy
Sometimes it's better to inline a style than to put it in a separate file.

I think when you find yourself writing nested selectors that are heavily
dependent on the HTML structure, it's an indication that your code could be
less fragile if you just used the HTML style attribute instead.

------
OstiaAntica
LESS CSS seems worth a look: <http://lesscss.org/>

------
joelanman
I try to code CSS starting with generic, going down to specific

Eg. Files would be something like:

* reset * global (eg header/footer) * common (stuff used most places but not all, eg. forms) * specific to section of the site * specific to the page

------
Nimb0z
Just run it through ProCSSor (<http://procssor.com> or <http://css.tl>). Lots
of options.

~~~
carterdea
that's an amazing resource. thanks

------
Flam
How I do it: 1 File. Single line styling. Order: Reset, html/body, header,
container, footer, misc (h1, p, span, input). Indent (ie: #header { }
-newline+tab- #header p {}

------
supervillain
Here's an example of a super organized CSS, with table-of-contents,
<https://www.mint.com/css/rd/mint.css>

------
monisninja
here's a simple way I organizate my CSS:

1\. reset.css 2\. global.css - reusable classes and styles for common
selectors (html, body, a, etc) 3\. css named per page (or type of a page) -
ex. home.css / about.css / results.css / static.css

* I usually add a class / id to the body and use that as my first selector on the page-level css. This allows me to combine all + minify for production

------
weallneedheroes
not really sure every way suits all but if it's kept as clean as possible &
organised it's always best.

Personaly i keep everything to do with each area to gether ie. Header, footer,
I wouldn't seperate out the <h> &

tags & place all the

's together.

if i'm working on a large site i tend to seperate out the css by section home,
Base template (about for example), contact, blog, news, shop...

------
pippy
ySlow recommends at most 3 stylesheets, and with good reason: the HTML headers
and request times can drastically slow a site down.

By simply organizing the structure of the file well, you can have a easy to
navigate css file. Of course there may be a few extra style sheets; ie.css,
section specific.css, print.css and mobile.css.

Here's my CSS file structure:

-reset

-html tags h1,p,q etc

-header

-navigation

-content

-sidebar

-misc (popups, forms, buttons)

-footer

~~~
elliottkember
It's generally a good idea to concatenate your stylesheets for production -
doesn't mean you have to write them as one big file, though.

------
dillon
Lots of comments really help, especially when you look at it months after.

------
ww520
I just use Blueprint.

------
weixiyen
I do it by widget and layout.

