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.
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:
Card Title
This is a simple card component.
/* 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:
The BEM methodology is a powerful way to keep your CSS organized, predictable, and scalable. By breaking down your components into blocks, elements, and modifiers, you can maintain cleaner code and avoid style conflicts, making development faster and more efficient as your project grows.
Ridoy Hasan
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3