I’m always on the lookout for thought-provoking discussion about CSS, since I find it so rare. Smashing Magazine can occasionally turn up quality information about CSS, as they did recently in a guest piece that described the nose-to-tail rebuild of the London Times’ website. An interesting read overall, the part that stood out most to me detailed their approach to CSS. They anticipated pain around HTML view re-use and re-composition (into various layouts), and sought to structure their CSS accordingly. I applaud their efforts (despite dropping the goal of semantic naming, which would seriously concern me), and noticed that it resembled an approach I had taken early in Blocvox’s development. I weighed in to share my experiences, and wanted to reproduce it here as a follow up to techniques described in my recent post about the motive for modular CSS.
Instead, I switched to a convention that relies on the child combinator. E.g.,
.apple { /* rules */ }
.apple > .-headline { /* rules */ }
.apple > .-headline > .-link { /* rules */ }
.apple > .-subHead { /* rules */ }
.apple > .-subHead > .-link { /* rules, can differ from header link */ }
.apple > .-body { /* rules */ }
The benefit of this comes when using a CSS preprocessor. I use Stylus, since I use Node.js for build tooling.
.apple
// rules
> .-headline
// rules
> .-link
// rules
> .-subHead
// rules
> .-link
// rules
> .-body
// rules
&._green
background-color: green
> .-headline
color: white
Now moving elements around only requires adding/removing a selector and indenting/un-indenting a bunch of declaration blocks. Performance is still good, but theoretically not as good as single class selectors.
A necessary part of this approach is that sub-elements have class names beginning with a dash, while root elements do not. A corollary is that all class names beginning with a dash are only used in selector groups scoped to a root class. With this convention, sub-elements are like private variables in OOP, with no meaning in the global class namespace.
I also use “flags” (e.g. “_green”, using an underscore prefix naming convention), which are analagous to a public boolean property in the OO world. Consumers are free to “set” any supported flag on a module’s root element.
No Comments Yet
Commenting options at bottom.