所以我一直在写我的类名,认为是正确的 BEM 。像这样的事情:
<div className="article">
<div className="article__textbox">
<h1 className="article__textbox--heading"></h1>
<p className="article__textbox--subheading"></p>
<span className="article__textbox--author"></span>
</div>
</div>
看看我是如何拥有文本框的,然后我里面的所有内容都给出了 2 个破折号?我最近发现这是无效的 BEM,现在我需要知道应该如何命名嵌套的东西。例如,我应该将 <p>
命名为什么?标签?
最佳答案
BEM的要点是元素(在类名中以 __
为前缀)和修饰符(以 --
为前缀)之间的区别:
Element
A part of a block that has no standalone meaning and is semantically tied to its block.Modifier
A flag on a block or element. Use them to change appearance or behavior.
在您的示例中,--heading
、--subheading
和 --author
都不是元素的修饰符 - 它们是元素。如果由于某种原因,您决定对这些元素应用实际的修饰符(例如 highlighted
或 clickable
),那么您最终要么完全重写类名,要么会出现一些奇怪的情况,例如article__textbox--标题--可点击
。
现在,我在这里看到的真正问题是“好吧,这不是修饰符,但是我应该如何处理位于其他元素内部的元素?”换句话说,哪些类名应该应用于嵌套在其他元素中的元素?这个问题实际上在BEM FAQ中有答案。 :
Q: What should I do if my block has a complex structure and its elements are nested? CSS classes like
block__elem1__elem2__elem3
look scary.A: According to BEM method, block structure should be flattened; you do not need to reflect nested DOM structure of the block. So, the class names for this case would be:
.block {}
.block__elem1 {}
.block__elem2 {}
.block__elem3 {}
... whereas the DOM representation of the block may be nested:
<div class='block'>
<div class='block__elem1'>
<div class='block__elem2'>
<div class='block__elem3'></div>
</div>
</div>
</div>
Besides the fact that the classes look much nicer, it makes the elements be dependent on the block only. So, you can easily move them across the block when providing changes to the interface. The changes of the block DOM structure would not need corresponding changes to the CSS code.
因此,就您的情况而言,将它们设置为这样的样式可能会更好:
<div className="article">
<div className="article__textbox">
<h1 className="article__heading"></h1>
<p className="article__subheading"></p>
<span className="article__author"></span>
</div>
</div>
另一种方法,在 this article 中有介绍。 ,将文本框视为一个单独的 block ,并将其所有内部结构视为其自己的元素:
<div className="article">
<div className="textbox">
<h1 className="textbox__heading"></h1>
<p className="textbox__subheading"></p>
<span className="textbox__author"></span>
</div>
</div>
请记住,这都是关于 DRY 的:如果该文本框打算在其他 block 中重用,请将其视为 block 。引用同一篇文章:
When you’re unsure if something even is a block, ask yourself: “Could this BEM element I’m about to add to a block be used as a component in other areas of the website?”
关于html - 这是为嵌套元素编写 BEM 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63950587/