0 CSS for Programmers: Part 1

Oh yeah, I’m looking at you. Let’s put away your recursive methods and pristine screen-scraping skills and dig into some CSS. It’s for your own good.

Cascading Stylesheets are not mysterious

I’m surprised at how many developers actually fear CSS. Considering it’s configuration/YAML style syntax you’d think a developer would soak it right up. But the opposite happens.

Just as designers think programming is a mysterious unattainable art so do programmers think about CSS. I’m here to tell you it’s not. CSS can be just as programmatic as the 100s of lines of back-end code you write on a daily basis. CSS shares at its core, some of the more programmatic philosophies. As a matter of fact, so does HTML. So lets learn together already! (Cue corny picture!)

CSS is loaded top/down

At an old job, I worked with a designer that didn’t grasp the fact that all CSS is loaded from the top down. They often organized their CSS definitions haphazardly and always wondered why things didn’t work as they should. CSS files are loaded top/down which also means you deal with namespace issues. A class definition at the bottom will take precedence over anything at the top with the same name. If something isn’t working correctly, the first thing to check for is definition duplication (and not IE foolery).

However, if you find yourself drowning in 1500+ lines of poorly organized CSS, there is hope. The trick to getting power over existing definitions is by inheritance traversals.


div.sidebar {
  background: #fff;
}

body #content div.sidebar {
  background: #999;
}

#content div.sidebar {
  background: #ccc;
}

In programming you have this concept of self and inheritance. The same applies in CSS. Naturally, #content doesn’t care about div.sidebar. However when you make div.sidebar an object of #content, then it has a reason to care. However if #content div.sidebar was missing the backround attribute, it would automatically inherit it from the stand-alone div.sidebar definition.

By traversing the DOM in your CSS definitions, you literally have the ability to non-destructively over-write any previously declared definition. You can see it in the example with body #content div.sidebar. Since body is the ultimate parent element and by traversing your definition all the way back to the body element, you have the ability to over-power any definition from any position in your CSS file. Pretty cool, eh?

Conclusion

Ya see? CSS can truly be programmatic in its logic. While this logic is very basic, it’s very powerful when you trying to hack Internet Explorer or fix a stylesheet that has been touched by 5 other designers (why that would ever happen? Couldn’t tell ya!).

Happy stylesheeting!

Use Textile for formatting