Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS BEM child tag selectors?

Tags:

css

bem

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:

  • Using BEM, can I reference tag selectors in my CSS..?
  • Using BEM, do all selectors in my CSS have to be class selectors..?
like image 776
Stephen Last Avatar asked Feb 05 '23 12:02

Stephen Last


1 Answers

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.

like image 84
csswizardry Avatar answered Mar 21 '23 06:03

csswizardry