Principles for writing good CSS
When taking a position at a new workplace, it’s important to explain to our colleagues what our tech background is. Making a point in a specific context is definitely easier when people understand what we stand for and why we stand for it. We sure have to be willing to change our development habits, but having strong beliefs about how software development should be done is also a good thing.
I gave it a shot and internally shared my views on how CSS development should be conducted:
- expressing intent and structure exclusively with classes (i.e., we shouldn’t have to rely on elements in our CSS). For instance the title of a post can be a
h1or adiv, both should look the same when applying a.post__titleclass to them - then when structure is defined, we can skin with stuff already existing in the styleguide (adding classes to elements, or with @mixins & @extends)
- a module/component/pattern should be easily exportable anywhere (for instance, comments blocks should not be tied to a post — they can exist on their own)
- whenever it’s possible, we should only use top level class selectors (no chaining nor nesting) (e.g.,
.unit__headeris better than.unit.header) - naming conventions are good, but prefixing classes with
b-(block),t-(template),l-(layout) has never been useful in my previous work. Jonathan Snook (SMACSS) and Nicolas Gallagher (Idiomatic CSS) preach for prefixing, so there is definitely a use case of it - classes should describe visual patterns as much as possible, not the content itself
- separation of concerns: JS and CSS should use different classes for behaviour hooks and styling
- don’t be afraid of being verbose in your HTML and CSS. Clarity is good!
- semantics are important. But when in doubt, just use a
divor aspan
References
- A New Front-End Methodology: BEM | Smashing Coding: very good article explaining in depth the principles behind BEM. Very good points in the comments against/for it
- Experimenting with component-based HTML/CSS naming and patterns: experiments from Nicolas Gallagher around naming conventions
- Idiomatic CSS: principles for writing consistent, idiomatic CSS. Sometimes a bit overkill but definitely a very good read
- An Introduction To Object Oriented CSS (OOCSS) | Smashing Coding: basic principles of OOCSS, a very good read even for people not applying the OOCSS approach in their code
- Taking Sass to the Next Level with SMURF and @extend: yet another approach, between SMACSS and OOSass, applying single responsibility and some other SOLID principles
6 notes
Comments