An Event Apart: Object Oriented CSS

by December 9, 2009

In her Object Oriented CSS talk at An Event Apart, Nicole Sullivan shared ways to optimize CSS code and ideas for the future of CSS.

  • CSS is a declarative language but there lessons it can take from object oriented languages
  • Developers should work with respect for the design. This makes code as beautiful on the outside as it is on the inside.
  • CSS code is often too fragile. It can get ruined by the first person to touch it. It needs to support more then just expert developers.
  • Browsers have default stylesheets and they are all different. YUI reset.css levels the playing field.
  • Browsers ignore styles that they don’t understand. You can use this to your advantage.
  • Order matters in CSS. Class order doesn’t matter inline but does in the stylesheet file. ID are stronger than classes. Inline styles will win over external stylesheets and those in the header. !important wins over everything.
  • Avoid inline, ID, and !important to allow cascade order to drive what gets implemented in CSS.
  • Object-orientated CSS is a way of making CSS more powerful. A focus on the architecture of elements not just the attributes.
  • Visual semantics and code semantics need to be in harmony with each other. Most people only see the visual hierarchy so it usually wins out.
  • Reusing elements makes them performance “freebies”. Avoid duplication: don’t waste performance resources that can’t add value. If too modules look too similar to include side by side on the same page –they are too similar to include on the same site. Choose one!
  • Location-dependent styles isolate sections of sites to avoid conflicts but they create performance problems. As developers try to use things, if they change based on location –they will simply create something new that does not change. Elements should behave predictability in any module.
  • Classes can help provide the additional styles needed without relying on location-dependent changes.
  • Use hacks sparingly. Don’t let them change the specificity of your code.
  • Style classes rather than elements. This allows things to get reused in other places.
  • Set up an abstract class to handle general structure so you don’t have to repeat lengthy declarations across multiple styles.
  • Use the most abstract class name you can while staying semantic.
  • IDs can only be used once in any given page. Don’t use them to style anything.
  • CSS wishlist: make it a better declarative language (need better ways to abstract reusable elements), make CSS easier for newbies.
  • Variables could make global changes easier. Could define up front and call within style declarations.
  • Prototypes could organize styles in patterns to reuse across a site.
  • Complexity can be abstracted out to the architectural level. There is no magic fix to make CSS easier but we can make it easier for beginners by requiring less code.