Rumata
Rumata

Reputation: 1047

How to name subelements according to BEM?

I have a question regarding BEM (Block Element Modifier) class naming conventions.

What if I need to have 3 nested divs, how should I name the class of the 3rd one?

.one{} //block
.one__two{} //block element
//?
<div class="one">
  <div class="one__two">
  
    <!-- How should I rename class "three"? -->
    <div class="three"></div> 
    
  </div>
</div>

I want to rename ".three" to "one__two__three", or "two__three", but I'm not sure that this is right, because as I understand, according to BEM nesting elements inside of elements is not allowed.

Upvotes: 1

Views: 284

Answers (2)

Martin
Martin

Reputation: 6136

Nesting elements is fine; build the structure to your needs. The important thing is to not couple the classnames to your nesting. The classname schema does really only recognize two types of DOM elements: the block itself and the elements of that block; of the latter all are equal regarding the naming schema, no matter how deeply nested in the block. Here is an example:

<div class="product-card">
  <div class="product-card__img-area">
    <img class="product-card__product-picture" src="https://example.com/cabulator.jpg"/>
  </div>
  <div class="product-card__header">
    <span class="product-card__main-headline">Encabulator</span>
    <span class="product-card__sub-headline">The turbo shmeerf of all Shmoof</span>
  </div>
  <div class="product-card__text-body">
    Lorem ipsum shmeerf of Shmoof quooz bar moof bla bla
  </div>
  <div class="product-card__footer">
    <a class="product-card__cta" href="https://example.com/buy.html">Buy it!</a>
  </div>
</div>

And modifiers are added as needed:

  <div class="product-card__footer">
    <a class="product-card__cta product-card__cta--bargain" href="http://exmpl.com/buy">
      Buy it! 50% off for first-time customers!!!!!! OMG!!!!
    </a>
  </div>

Upvotes: 0

seantunwin
seantunwin

Reputation: 1768

To me, it's about relationships, particularly key-value relationships, so I would approach it that way.

Without exploring contextual naming paradigms, it could be suggested to use one__three.

Alternatively, if one is simply a container for two, then one could be renamed two__container and three renamed to two__item. Of course that doesn't make a whole lot of sense using numbered labels like this, but I hope you can see where it could lead.

Upvotes: 1

Related Questions