Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child element of modifier element?

Tags:

html

css

bem

Take the following structure:

<div class='article article--yellow'>
  <div class='article__headline'>...</div>
</div>

<div class='article article--blue'>
  <div class='article__headline'>...</div>
</div>

If I need to make article__headline different for --yellow from --blue, should I do a CSS selector like:

.article--yellow .article__headline { ... }

Or, in the practice of minimizing selection-depth, is it valid BEM syntax to change the markup to this:

<div class='article article--yellow'>
  <div class='article--yellow__headline'>...</div>
</div>

Because then I could select it using only 1 selector: article--yellow__headline.

I know that technically it would work, but I can't figure out if this is valid according to BEM methodology or not.

like image 409
Jake Wilson Avatar asked Feb 08 '23 07:02

Jake Wilson


1 Answers

This is a perfect question and bem's faq actually answered it!

Can a block modifier affect elements?

If I have a block modifier, for example xmas, and I want the elements within that block to also be xmas themed, how would it be best to do it.

Does a --xmas suffix for every element seem necessary? Or would this be the one use-case for nesting (e.g. block--xmas block__elem { ... } ?

However in general BEM recommends to avoid nested selectors, this is the case when they are reasonable.

When creating the nested selector, you declare that one entity depends on another. As BEM introduces independent components, such an approach is not suggested when we are speaking about 2 different blocks.

But when it comes to a block and its element, they are not of equivalent meaning. By it definition, an element does not make any sense outside its parent block. So, an element is a block-dependent entity. Assuming this, it is quite normal and logical that an element is affected by the block's current state.

So, this is quite a pattern in BEM to code

.my-block--xmas .my-block__button {
    /* Jingle bells, jingle bells, jingle all the way.*/ }

So the answer should be your first approach

.article--yellow .article__headline { ... }
like image 62
Ahmad Alfy Avatar answered Feb 13 '23 06:02

Ahmad Alfy