DEV Community

loading...

Discussion on: BEM Methodology In CSS: A Quick Start Guide

Collapse
codypearce profile image
Cody Pearce

Nice guide! How would you handle components that have more levels of elements? For example,

card
  card__header
    card__title
    card__subtitle
  card__body
    card__title
 ...etc

Or

card
  card__header
    card__header__title
    card__header__subtitle
  card__body
    card__body__title
 ...etc

Or

card
  card__header
    cardHeader__title
    cardHeader__subtitle
  card__body
    cardBody__title
 ...etc
Collapse
scalablecss profile image
Tom Ray Author

Thanks for the question Cody!

Your first solution is recommended BEM best practice, so I would stick with that.

In fact, don't just take my word for it ;). Here's a quote taken from one of the guys who is working on the BEM methodology over at Yandex:

"BEM methodology doesn't recommend to use elements within elements in class names. You don't need to resemble DOM structure in naming. Having one level structure makes refactoring much easier."
— Vladimir Grinenko, Yandex

I actually wrote a full blog post already answering your question:
scalablecss.com/bem-nesting-grandc...

Hope this helps!

Collapse
dirtycode1337 profile image
Dirty-Co.de

Your block is card, so last thing wouldn't match, because of cardHeader - writing.

The second way is the way I would go, because it keeps classes "unique" for each element, so a header title and a body title cannot be accidentally switched by the notation like in the first example.

I would finally write that this way:

card
    card__header
        card__header-title
        card__header-subtitle
    card__body
        card__body-title
        card__body-content 

This would also finally lead to really small SASS code, which I would prefer before CSS ;) :

.card{
    //properties for the whole card block
    &__header{
        &-title{

        }
        &-subtitle{

        }   
    }
    &__body{
        &-title{

        }
        &-content{

        }
    }
}

I don't see a problem in dividing element or block names with a single - for better readability.

Also you could mix up two blocks within a card block here like you have a card block including a header block and a body block, if header and body blocks are logically seperated like:

card
    header
        header__title
        header__subtitle
    body
        body__title
        body__content

But I would use my example before in this case :)