13.5 Semantic use of classes instead of generic names
Using semantic class names means choosing names that describe the role or meaning of an element rather than its appearance. This leads to more maintainable, reusable and understandable markup. Avoid names like box, red or big-text and prefer names that reflect the component’s function or context, for example notification, badge or error-message.
The Problem with Generic Class Names
-
Low reusability –
red-textcannot be used when you need blue, green or responsive typography. - Poor maintainability – changing a “generic” style may have unintended effects throughout the site.
-
Hard to grasp intent – future developers cannot infer why an element was styled simply from a class like
boxorfloat-left.
Example of generic classes:
Warning!
Principles of Semantic Class Naming
- Reflect intent: name classes after what they represent, not how they look.
-
Make them context-aware: if this is a button inside a form, consider
form__submitrather thanbtn-blue. - Avoid presentation details: remove color, size or positioning from class names.
-
Use modifiers sparingly: for small, predictable variations (e.g.
button--disabled,alert--error).
Naming Methodologies
Several popular conventions enforce semantic naming:
-
BEM: block__element–modifier. Example:
card__title--highlighted. - SMACSS: categorizes classes into Base, Layout, Module, State, Theme.
- OOCSS: separates structure from skin and container from content.
Semantic Class Example: Notification Component
Compare a generic version versus a semantic version of a notification box.
Form submission failed.
notificationis the block (a reusable module).notification__iconandnotification__contentare elements.notification--erroris a modifier indicating the error variant.
Benefits of Semantic Classes
- Clarity: markup describes purpose rather than presentation.
- Scalability: components can be refactored or restyled without changing HTML semantics.
- Team collaboration: everyone speaks the same naming language (via BEM, SMACSS, etc.).
- Ease of overriding: state modifiers like
is-activeornotification--successare explicit.
Practical Tips
- Start with a naming convention guideline in your project.
- Review existing CSS for generic names and refactor them semantically.
- Document your patterns (blocks, elements, modifiers).
- Use linters or naming plugins to enforce consistency.
By choosing semantic class names, you decouple structure from styling details and create a more robust, understandable, and maintainable codebase.
Leave a Reply
You must be logged in to post a comment.