Stephen Last
Stephen Last

Reputation: 5781

CSS BEM child tag selectors?

Using CSS BEM methodology...

Say I have some HTML, something like this (which is just example HTML made up for this question):

<section>
  <div>
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
  </div>
</section>

From what I've read, I should be doing this:

.section { ... }
.section__sometext { ... }
.section__text { ... }

<section class="section">
  <div class="section__sometext">
    <p class="section__text">Text.</p>
    <p class="section__text">Text.</p>
    <p class="section__text">Text.</p>
    <p class="section__text">Text.</p>
    <p class="section__text">Text.</p>
  </div>
</section>

Rather than this:

.section {}
.section__sometext { ... }
.section__sometext p { ... }

<section class="section">
  <div class="section__sometext">
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
    <p>Text.</p>
  </div>
</section>

Is it ok to use .section__sometext p { ... }..?

The problem I have is that there may be lots and lots of p's, and giving them all long class names just seems like a waste of time and markup.

Using .section__sometext p { ... } will only ever style p's within the section__sometext element, within the section block.

UPDATE

I do realise that there are several different variations of BEM. There seems to be no hard-and-fast spec to refer to which talks about this issue. But I'm really asking this question with a view to following BEM as close as possible.

So my question really is asking:

Upvotes: 5

Views: 1653

Answers (1)

csswizardry
csswizardry

Reputation: 591

My advice would be to stay pragmatic; don’t follow anything to the letter just because. Take whichever approach feels best right now (it sounds like you’re leaning toward .section__sometext p {}), and if it turns out to have been the wrong thing then refactor it later.

This is general advice I would hand out to anyone: instead of being paralysed, just do something and see how it pans out. It might work perfectly, and if not then you can just refactor it later.

Upvotes: 9

Related Questions