BEM and single selectors

This is kind of a theoretical question, but it has been bothering me for a couple of hours now.

I am learning BEM, which is great, but I have a problem. Let's say I have this code:

<div class="section-hi main-section">
  <h2 class="main-section_header">Blah</h2>
  <p>Generated from the CMS</p>
</div>

      

How do I target p

to make it good with BEM? Can I just go with

.main-section p

      

or would it be against the rules? I can't seem to find answers to this as every BEM example and article focuses only on classes and I can't expect my CMS to add a different class to every paragraph group.

+3


source to share


2 answers


One of the concepts in BEM is to create reusable components, using an element such as p

is contrary to this.

Why?

By specifying p

, we are limiting how our component can be used. The tag p

must be used to display correctly . For example, the following markup will not work with a component.

<div class="section-hi main-section">
  <h2 class="main-section_header">Blah</h2>
  <span>Generated from the CMS</span> <!-- this will not pick up the styles -->
</div>

      

Specificity

Another important point is that BEM strives to keep certainty to a minimum, using the names of the same class. Styling with p

increases the specificity.

.main-section p

      

Now I find it difficult to override this style with a utility class as it has higher specificity than one class.

More on Specific CSS



Decision

So the idea instead is to use class names to describe the element. This way, we can use any markup we like and the component will render as expected. eg.

<div class="section-hi main-section">
  <h2 class="main-section_header">Blah</h2>
  <h3 class="main-section_subHeader>Generated from the CMS</h3> <!-- This will work -->
</div>

      

Should I always use class names?

You will find cases where this is okay or where you need to style the elements rather than using class names. For example, you might have a component that you only want to use with certain markup. Then it is perfectly true for that.

Summary

As a general rule, always try to stick to the single class rule unless there is a compelling reason not to. Otherwise, it will disconnect you later down the line.

For further reading on BEM I recommend this post http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/

+5


source


If we just look at this code, you can do it, but what if you have more items <p>

? If you cannot add a class to every element, you can always add id

and call an element



 #element_id{ }

      

-4


source







All Articles