Some CSS Best Practices and Their Caveats, Part 1
Over the last several years, I’ve slowly accumulated a set of principles for good, maintainable front-end code, especially CSS. Here are my thoughts on some of them.
Composing in the Browser
In 2009, a colleague pointed me in the direction of Object-oriented CSS (OOCSS), and it was a real eye-opener for me. I started to take a more engineering-like approach to CSS; I started learning more of the under-the-hood stuff. Up to that point I had a really loose grasp of things like floats and standard-vs-IE box models.
One of the key concepts is that you apply multiple classes to your HTML elements, “mixing in” properties. The classes become smaller and simpler and more reusable. And your core library stays small, because there are fewer classes.
Caveat: developing an OOCSS library on an already-running project can be tricky. Reusable styles that are in flux can easily become unnecessary interdependencies, as you tweak your class you may break things elsewhere in your site or application.
Other solid principles coming from OOCSS:
- Be flexible – use fluid layouts.
- Use separate classes/elements for layout.
- The width of a component should be dictated by its container (e.g., a grid column).
- The height of a component should be dictated by its content.
- Separate structure and skin.
- Separate container and content.
- Define element styles once, then never include them in a selector after that.
- Don’t use IDs.
The OOCSS approach is still a foundation for MOST of the good CSS libraries/philosophies out there today.
More to come:
- The architecture of your selectors is super important
- Develop your core library in isolation
- Non-semantic classnames are just fine in some cases
- BEM (Block, Element, Modifier) can be a lifesaver
- DRY is good — but don’t “pre-factor”
- Don’t worry about CSS performance until it’s an actual problem
- Use SVG for icons, interface elements, and flat artwork