In this article, we’ll dive into the BEM (Block, Element, Modifier) methodology, a popular CSS naming convention that helps you write clean, structured, and maintainable CSS for large projects. BEM ensures that your code remains scalable as the project grows and reduces the chances of style conflicts.
BEM stands for:
The BEM methodology emphasizes creating reusable, predictable, and maintainable CSS code.
.block {} .block__element {} .block--modifier {}
Let’s break down the structure of BEM with an example.
<div class="menu"> <ul class="menu__list"> <li class="menu__item menu__item--active">Home</li> <li class="menu__item">About</li> <li class="menu__item">Contact</li> </ul> </div>
In this example:
A block is an independent, reusable component. Think of it as a self-contained entity that can be placed anywhere in your code without worrying about its style being affected by other elements.
.button { padding: 10px 20px; background-color: #3498db; color: white; border: none; }
Here, .button is a block that defines the styles for a button component. You can reuse this block across multiple parts of your website.
An element is a part of a block that has no standalone meaning. It’s tied to the block and exists to perform a function related to the block.
.button__icon { margin-right: 10px; } .button__label { font-size: 14px; }
Here:
A modifier represents a variation of a block or element. Modifiers are used to change the appearance or behavior of a component, such as changing the color of a button or making an element larger.
.button--primary { background-color: #2ecc71; } .button--large { padding: 15px 30px; }
Here:
Modifiers can also be applied to elements:
.button__icon--small { width: 10px; height: 10px; }
Let’s look at a more complete example that includes blocks, elements, and modifiers:
<div class="card"> <div class="card__header"> <h2 class="card__title">Card Title</h2> </div> <div class="card__body"> <p class="card__text">This is a simple card component.</p> </div> <div class="card__footer"> <button class="button card__button card__button--primary">Read More</button> </div> </div>
/* Block */ .card { border: 1px solid #ddd; padding: 20px; border-radius: 5px; } /* Elements */ .card__header { margin-bottom: 15px; } .card__title { font-size: 18px; color: #333; } .card__body { margin-bottom: 15px; } .card__text { color: #666; } .card__footer { text-align: right; } /* Modifier */ .card__button--primary { background-color: #3498db; color: white; }
In this example:
BEM 方法是保持 CSS 有序、可预测和可扩展的强大方法。通过将组件分解为块、元素和修饰符,您可以维护更清晰的代码并避免样式冲突,从而使您的项目开发更快、更高效成长。
里多伊·哈桑
The above is the detailed content of CSS BEM Model – A Guide to Writing Scalable and Maintainable CSS. For more information, please follow other related articles on the PHP Chinese website!