
As I’ve begun implementing more complicated layouts with CSS, I’ve encountered a problem: naming CSS classes and ids meaningfully can be difficult.
Names that aren’t descriptive enough to inform you of their purpose force you to figure out what they do, which isn’t always a good use of time. Furthermore, working on someone else’s project is difficult if they’ve used naming conventions meaningful to them but no one else.
The solution? CSS naming conventions and methodologies. The following are some methodologies that attempt to make CSS easier to read and maintain:
- BEM (Block, Element, Modifier)
- OOCSS (Object-Oriented CSS)
- SMACSS (Scalable and Modular Architecture for CSS)
- SUITCSS (“a styling methodology for component-based UI development”
- Atomic – (“the approach to CSS architecture that favors small, single-purpose classes with names based on visual function”)
Of the methodologies listed above, BEM might be the least complex. As explained in this article by freeCodeCamp, if we were looking at a drawing of a stick figure:
- B – stands for block. More specifically, a block of design that is thought of as a parent (according to CSS-Tricks). Going back to our stick figure example, “.stick-man” would be a good class name.
- E – stands for element(s). Elements are children of the block component and are represented by two underscores. In our stick figure example, the stick man’s head, arms, and legs would be elements. So, “.stick-man__head” would be a good class name for the stick man’s head.
- M stands for modifier(s). Modifiers are changes made to a specific element and are denoted by two hyphens added to the class name. For example, if we wanted to make our stick figure blue, we could use the class name, “.stick-man–red.” To make a stick man with a large head, we would use “.stick-man__head–large.”
Check out these articles to learn more about CSS naming conventions and read more about BEM:
- freeCodeCamp – CSS Naming Conventions that Will Save You Hours of Debugging
- CSS-Tricks – BEM 101
- HackerNoon – Best Practice in CSS: Organisation and Naming Conventions
- GetBEM.com – provides an overview of BEM
- Matt Fairbrass’ Medium Article – SUIT CSS
- CSS-Tricks – Let’s Define Exactly What Atomic CSS Is
- Swapps.com – What is SMACSS and how to use it
- Smashing Magazine – An Introduction to Object Oriented CSS