Writing scalable and maintainable CSS can be challenging. CSS naming conventions like BEM, OOCSS, and SMACSS help improve code structure, readability, and reusability.
1. BEM (Block-Element-Modifier)
BEM (Block-Element-Modifier) is a methodology that makes CSS more modular and reusable by using a structured naming convention.
Structure:
- Block: Represents a standalone entity (e.g.,
.button,.nav). - Element: A part of a block, dependent on it (e.g.,
.button__icon). - Modifier: A variation of a block or element (e.g.,
.button--large).
Example:
/* BEM Example */
.button {
background: blue;
color: white;
padding: 10px 20px;
}
.button--large {
font-size: 18px;
padding: 15px 30px;
}
.button__icon {
margin-right: 5px;
}
2. OOCSS (Object-Oriented CSS)
OOCSS (Object-Oriented CSS) promotes reusability by separating structure from skin.
Principles:
- Separation of Structure and Skin: Keep layout (e.g., grid) separate from visual styles (e.g., colors).
- Reusability: Use generic class names to avoid repetition.
Example:
/* OOCSS Example */
.box {
padding: 20px;
border-radius: 5px;
}
.box--primary {
background-color: blue;
color: white;
}
Reusable Box
3. SMACSS (Scalable and Modular Architecture for CSS)
SMACSS is a modular CSS architecture that categorizes styles into five groups:
- Base: Default styles for elements (e.g.,
body,h1). - Layout: Defines major page sections (e.g.,
.header,.sidebar). - Module: Reusable components (e.g.,
.card,.button). - State: Defines variations (e.g.,
.is-active,.is-hidden). - Theme: Custom styling for themes (e.g.,
.theme-dark).
Example:
/* SMACSS Example */
.button {
background: gray;
color: white;
padding: 10px;
}
.button.is-active {
background: green;
}
Conclusion
Choosing a CSS naming convention like BEM, OOCSS, or SMACSS improves code readability and reusability. Each approach has its strengths, so use the one that best fits your project.