Search code examples
bem

BEM: Nested Blocks, what is the best approach?


In the following markup, what is the best BEM approach?

This?:

<footer role="footer">
  <footer class="footer__inner">
    <div class="footer__left">© Some text</div>
    <div class="footer__right">Some text</div>
  </footer>
</footer>

OR this?:

<footer role="footer">
  <footer class="footer__inner">
    <div class="footer__inner__footer__left">© Some text</div>
    <div class="footer__inner__footer__right">Some text</div>
  </footer>
</footer>

Or none of them are right and you know a better way?

Thanks


Solution

  • You want to have clean reusable blocks. Ask yourself which part you might want to reuse.

    Multi level nesting of blocks are frowned upon. And that's for a good reason. In case of reusability there should only be one block as root reference. Everything below that one block is, from a bem syntactic point of view, simply an element of that block. Not a sub-block, not a sub element, but only an element.

    So, BEM doesn't care about your HTML structure. It's much more a question of what purpose a block or an element has.

    I can't really tell from your example what the purpose of your nested footers might be, but it looks to me as if you consider the role attribute of your outer footer element as part of BEM-naming. But it's not. Keep in mind the idea of separation of concerns. role="footer" is HTML semantic. You should not use it as BEM naming reference because you might want to change that HTML attribute one day and then your BEM semantic would go up in smoke.

    So, here's what I would do.

    Let's say you want your outer footer to be the reusable element then you might want to name your classes like this (just as an example):

    <footer class="footer" role="footer">
        <footer class="footer__textbox">
            <div class="footer__text footer__text--left"> <!-- left as modifier -->
            <div class="footer__text footer__text--right"> <!-- right as modifier -->
        </footer>
    </footer>
    

    Now you can take your footer and use it in any appropriate section of the page and anyone reading your code can get grasp an idea about the purpose of this css structure.