title: How to remove CSS spaghetti in legacy web app?
body: <p>After working on several large web applications, and seeing gigantic style sheets with no clear structure, I'd really love to know if people have found ways to keep their css clean for large and complicated web apps. </p>
  
  <p>How do you move from a legacy, mess of css to cleaned up, nicely cascading, DRY stylesheets?</p>
  
  <p>The app I'm currently working on has 12000 lines of css. It's grown to this size organically as early on there were no standards or review of the css, the only rule was to make the app match the design. Some of the problems we constantly have:</p>
  
  <ul>
  <li><p>Conflicting styles: one developer adds a .header { font-weight: bold;} but .header was already used in other modules and shouldn't be bold in those.</p></li>
  <li><p>Cascading problems: Foo widget has a .header but it also contains a list of Bar widgets with .header classes.</p>
  
  <ul>
  <li>If we define .foo .header { ... } and .bar .header { ... } anything not explicitly overwritten in foo will show up in bar.</li>
  <li>If we define .foo > .header and .bar > .header but later need to modify foo to wrap header in a div, our styles break.</li>
  </ul></li>
  <li><p>Inheritance problems, we constantly redefine widget fonts to 11px/normal because some top container uses a 12px / 18 px line height.</p></li>
  <li><p>Fighting against widget libraries, using libraries such as dojo/dijit or jquery ui that add tons of styles to be functional means that our code is littered with places where we have to override the library styles to get things looking just right. There are ~2000 lines of css just for tweaking the builtin dijit styles</p></li>
  </ul>
  
  <hr>
  
  <p>We're at a point where we're thinking of implementing the following rules:</p>
  
  <p><strong>Namespace all new widget classes</strong> - if you have a widget foo all sub-classnames will be .foo_ so we get: .foo, .foo_header, .foo_content, .foo_footer. This makes our css essentially FLAT, but we see no other way to organize our code going forward without running into the legacy styles or the cascading problems I mentioned above.</p>
  
  <p><strong>Police generic styles</strong> - have a small handful of generic classes that are only to be applied in very specific situations. e.g. .editable - apply to portions of a sentence that should invoke an editor - should only contain text nodes.</p>
  
  <p><strong>Leverage css compiler mixins</strong> To avoid repeatedly defining the same styles in different widgets, define and use mixins. Although we worry the mixins will get out of control too.</p>
  
  <p>How else can we move from css mess that constantly introduces regressions to something maintainable going forward.</p>