BEM命名规范中block__element__element与block__element-element的区别及命名疑问
Great question! BEM naming can feel a bit confusing when you're navigating edge cases like these, so let's break this down clearly.
1. Difference between block__element__element and block__element-element in BEM
First, a quick recap of BEM's core rules to set context: BEM stands for Block, Element, Modifier. Elements are parts of a Block that can't exist on their own, and their naming should only tie them to their parent Block—not mirror the DOM's nested structure.
block__element__element: This is invalid BEM syntax. The double underscore__is exclusively used to link a Block to its direct Elements. Writing something likemenu__item__titleincorrectly implies thattitleis an Element ofmenu__item, but BEM doesn't allow Elements to have their own sub-Elements. This approach mixes up DOM hierarchy with BEM's structure, which defeats one of BEM's biggest strengths: keeping class names decoupled from HTML structure.block__element-element: This is valid BEM syntax. Here,element-elementis just a multi-word Element name, separated by hyphens (BEM recommends hyphens for multi-word names to keep things readable). For example,menu__item-titlerefers to a "title that belongs to a menu item"—it's a single Element of themenuBlock, with a descriptive name that makes its role obvious.
2. Distinguishing the menu's title vs. menu item titles
If your menu Block has its own title and each menu__item also has a title, the solution is to use distinct, role-based Element names to tell them apart:
Option 1: Keep everything within the menu Block
- Use
menu__titlefor the main menu title (the one attached directly to themenuBlock itself). - Use
menu__item-titlefor the title inside eachmenu__itemElement.
Your HTML would look like this:
<div class="menu"> <div class="menu__title">Main Menu</div> <div class="menu__item"> <div class="menu__item-title">Home</div> </div> <div class="menu__item"> <div class="menu__item-title">About</div> </div> </div>
Option 2: Elevate menu__item to its own Block (for reusability)
If menu__item might be used independently of the menu Block (e.g., in a sidebar, dropdown, or other component), you can turn it into a standalone Block called menu-item. Then:
- Use
menu__titlefor the main menu title. - Use
menu-item__titlefor the title of eachmenu-itemBlock.
Here's what that HTML would look like:
<div class="menu"> <div class="menu__title">Main Menu</div> <div class="menu-item"> <div class="menu-item__title">Home</div> </div> <div class="menu-item"> <div class="menu-item__title">About</div> </div> </div>
The core idea here is that BEM relies on descriptive, purpose-driven names rather than DOM nesting. As long as each Element's name clearly communicates its role (either within the parent Block or as a standalone Block), you'll avoid any confusion between the two titles.
内容的提问来源于stack exchange,提问作者chickenDinner

