Search code examples
htmlcssbem

Am I allowed to use element from a parent block, inside a children block?


I would like to know if, according to BEM methodology, I can have the following structure:

.block1
  .block1__element1
    .block2
       .block1__element2 <-- ??

Am I allowed to use an element from a parent block, inside a children block?

Thanks.

UPDATE:

This is the actual DOM structure:

<div class="head">
  <div class="head__user"></div>
  <div class="head__nav">
    <div class="menu">
       // <-- ???
    </div>
  </div>
</div>

According to best practices of BEM methodology: am I allowed to move the element with head__user inside the menu block? Or all elements inside the menu block need to start with the menu__ prefix?

I hope this clears out the problem.


Solution

  • I think this variant is allowed:

    <div class="head">
      <div class="head__nav">
        <div class="menu">
           <div class="head__user"></div>
        </div>
      </div>
    </div>
    

    I haven't found the current part in the official BEM documentation, but I've found this part:

    The block name defines the namespace, which guarantees that the elements are dependent on the block (block__elem).

    A block can have a nested structure of elements in the DOM tree:

    Example

    <div class="block">
        <div class="block__elem1">
            <div class="block__elem2">
                <div class="block__elem3"></div>
            </div>
        </div>
    </div>
    

    However, this block structure is always represented as a flat list of elements in the BEM methodology:

    Example

    .block {}
    .block__elem1 {}
    .block__elem2 {}
    .block__elem3 {}
    

    This allows you to change a block's DOM structure without making changes in the code for each separate element:

    Example

    <div class="block">
        <div class="block__elem1">
            <div class="block__elem2"></div>
        </div>
        <div class="block__elem3"></div>
    </div>
    

    The block's structure changes, but the rules for the elements and their names remain the same.

    I understand it as there is only one rule about HTML structure for elements in BEM: an element has to be inside its block (it doesn't matter how deep).

    One possible problem that I can imagine for this case is using some of BEM tree formats. But if you don't need it, I think there's no problem.