html - 修饰符元素的子元素?

标签 html css bem

采用以下结构:

<div class='article article--yellow'>
  <div class='article__headline'>...</div>
</div>

<div class='article article--blue'>
  <div class='article__headline'>...</div>
</div>

如果我需要使 article__headline--yellow--blue 不同,我应该做一个 CSS 选择器吗:

.article--yellow .article__headline { ... }

或者,在最小化选择深度的实践中,是否将标记更改为有效的 BEM 语法:

<div class='article article--yellow'>
  <div class='article--yellow__headline'>...</div>
</div>

因为这样我就可以只使用 1 个选择器来选择它:article--yellow__headline

我知道从技术上讲它会起作用,但我无法确定根据 BEM 方法这是否有效。

最佳答案

这是一个完美的问题,bem's faq actually answered it !

Can a block modifier affect elements?

If I have a block modifier, for example xmas, and I want the elements within that block to also be xmas themed, how would it be best to do it.

Does a --xmas suffix for every element seem necessary? Or would this be the one use-case for nesting (e.g. block--xmas block__elem { ... } ?

However in general BEM recommends to avoid nested selectors, this is the case when they are reasonable.

When creating the nested selector, you declare that one entity depends on another. As BEM introduces independent components, such an approach is not suggested when we are speaking about 2 different blocks.

But when it comes to a block and its element, they are not of equivalent meaning. By it definition, an element does not make any sense outside its parent block. So, an element is a block-dependent entity. Assuming this, it is quite normal and logical that an element is affected by the block's current state.

So, this is quite a pattern in BEM to code

.my-block--xmas .my-block__button {
    /* Jingle bells, jingle bells, jingle all the way.*/ }

所以答案应该是你的第一种方法

.article--yellow .article__headline { ... }

关于html - 修饰符元素的子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558735/

相关文章:

jquery - 文本的 CSS 放置

css - 坚持模块化样式

css - 什么是 BEM 方法论?

html - MVC/ Razor : Conditional nested html tag

javascript - 如何将按钮更改为可单击的文本,以执行与按钮相同的操作

javascript - JQuery 验证 - 文本输入所需的单选按钮

导航栏的 CSS Bootstrap 背景颜色在折叠的导航中不可见

css - BEM CSS block 或修饰符

c# - 带有文本框和按钮的 Repeater 中的 DefaultButton?

php - 表单内的表单 HTML