What’s Your Preferred CSS Class Naming Convention?
- BEM (Block Element Modifier)
- SMACSS (Scalable and Modular Architecture for CSS)
- OOCSS (Object-Oriented CSS)
- Atomic CSS
- Others
There are various naming conventions for CSS classes, each with its own advantages. What conventions do you use, and why do you prefer them?
Are you more of a dash (-) or underscore (_) person when naming CSS classes?
I've been looking for a solid CSS convention for a while, but don't really like any of them.
style=
, marketed to make you feel less bad about something that's still just as bad for you.What I've personally landed on is an approach that emphasises short selectors with few conditions, reliance on custom properties and a general ideal of using as few "helper" classes as possible.
Generally speaking, I aim for the following:
To achieve this, I often make use of custom elements, which can be surprisingly convenient even without registering them in JavaScript.
For example, I might end up with HTML that looks like this:
flex-column
tag tells you what the thing is much more quickly than seeing a<div>
and having to filter through a long list of classesgap=2
attribute communicates clearly that there is an attribute name and a value, unlike, say, a.gap-2
class, which takes some more focus to decipher.button
and genericdanger
utility classes don't really fit into any of the other categores, so they end up just being classesWhat I wish I could do is communicate the difference between utility classes like
.danger
and those that really express a different class of whatever the tag represents, like.slider
on a checkbox.In the end, what I end up with is somewhere in between OO, Atomic and Axiomatic CSS. Apart from that, I mainly try keeping the number of element types low and not make up a dozen new elements for every page. Something I can get away with because there's no designer wanting this one particular button to have just a little bit more padding on desktop.
If you want some examples of what this ends up looking like in practice, feel free to have a look around this website for an (unfinished!) css library I'm working on.