In a previous post, I said:
Shoehorning CSS and HTML into PHP abstractions prevents the code from being DRY and ultimately leads to code bloat, because, the CSS and HTML require a far more granular object structure than the PHP.
And then I didn’t expand on it, or give proper context. Ooops, sorry!
Correct granularity is one of the keys to tiny CSS
In the PHP layer, the following stream story (from facebook) might be a single object. All of the logic of determining which bits of HTML to show or hide are contained within one object structure.
Frequently, developers try to make the CSS match this middle-end logic. We expect all the CSS code for the stream story to be sand-boxed within a wrapper id, for example #story. This ends up with bloated code that isn’t DRY. Why? because the proper architecture for the CSS layer is much more granular. Trying to base the CSS architecture on the PHP layer is something akin to trying to use the DB schema to configure apache. It just doesn’t work.
So we can see that the stream story example above is composed of many more granular objects. As we make the objects more granular, we begin to see the same patterns emerge over and over, and the same objects become much more reusable. We start to see that most sites on the interwebs are composed of the same basic repeating patterns combined in different ways. As a side benefit, the CSS gets *much* smaller and simpler.
The stream story, one PHP object, is composed of several HTML & CSS objects:
5 Media Blocks
2 Link Styles
1 Comments List
1 Action List
Benefits of this approach?
Getting the CSS object granularity right means that our CSS (and by extension, our HTML) become much simpler and lighter. Our little reusable object can be employed across the site to create new and different pages without adding to the weight of the CSS.
As a starting point, I recommend creating the following objects: headings, lists, text treatments and links, containers, media, grids, and template. Create all your smallest objects first, before you build whole pages, and your CSS will stay small by default.