Can we make an element of block modifier in BEM?

2019-07-22 20:01发布

I just wanted to know whether the following code follows BEM methodology best practices? Creating an element for the block modifier i.e. in this case "block--mod" is a modifier for the "block" block. Is it allowed to create a nested element with this pattern: "block--mod__elm".

<div class="block block--mod">
   <div class="block__elm block--mod__elm">
</div>

标签: html css bem
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-22 20:24

In situations like theming or similar I would use nested selectors. This saves some classes in your HTML and as @Jonathan Nicol said those sub-elements can be hard to follow. Also it will be easier to remove the "branding" later, just remove block class instead of all it's elements.

For example Xmas branding of your header.

.header--xmas .header__logo {
    /* Jingle bells, jingle bells, jingle all the way.*/
}

Source: http://getbem.com/faq/#can-a-block-modifier-affect-elements-

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-22 20:25

I could not find an example of a the .block--mod__elem pattern in Yandex's BEM documentation (Yandex devised the BEM methodology), but an early article about BEM on CSS Wizardry does show an example of a modifier with a sub-element, .person--female__hand:

.person {}
.person__hand {}
.person--female {}
.person--female__hand {}
.person__hand--left {}

Source: MindBEMding – getting your head ’round BEM syntax

Modifiers with sub-elements can be a little hard to follow, but I do not shy away using from them if it seems like the logical approach.

Edit: @NikolayMihaylov's answer gives an alternative approach that I wholeheartedly support. It is more readable and more maintainable.

查看更多
登录 后发表回答