问题
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>
回答1:
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-
回答2:
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.
来源:https://stackoverflow.com/questions/47338574/can-we-make-an-element-of-block-modifier-in-bem