Search code examples
cssbem

Elements without class name?


I have a super simple question, are children elements allowed to be classless in BEM CSS methodology?

So, is this code valid:

<div class="foo__label">
  <p class="foo__text">Something <strong>else</strong></p>
</div>

Or maybe it should be written as:

<div class="foo__label">
  <p class="foo__text">Something <strong class="foo__text-strong">else</strong></p>
</div>

Solution

  • I will allow myself to quote @Intervalia:

    Your first example is fine. In your second example you only need to add a class if you plan to create CSS for it. class="foo__text-strong" is needed if you need it to be.

    His comment perfectly answers your question. However I would like to add another scenario which may come in handy.

    It is regarding user generated content from a CMS (worpdress for example). In this scenario the user is usually writing content in WYSIWYG editor and can not add BEM classes or even the user is not so advanced to know about them.

    In this case is perfectly fine to have a "parent" element in which you can style elements by tags.

    Examples:

    .text ul{}
    .text p{}
    .text iframe{}
    .text img{}
    .text strong, .text b{}
    .text em, .text i{}
    .text a{}
    

    UPDATE 1: Info on using nested selectors:

    Nested selectors increase code coupling and make reuse impossible. The BEM methodology allows using nested selectors, but we recommend minimizing their use. https://en.bem.info/methodology/faq/#can-i-use-nested-selectors

    So yeah if you think it is overkill you may go with @Rene's suggestion.

    UPDATE 2: Helper Classes.

    The BEM methodology doesn't have strict rules for creating helper blocks. A lot depends on specific implementations and the personal preferences of the developer. An example of a helper block in bem-core is the clearfix block. https://en.bem.info/methodology/faq/#can-i-create-helper-classes

    Perhaps this technique can help? Personally I always have few global helpers which I use a lot.

    Example, the famous Screen Reader only styles:

    .sr-only{
        position: absolute;
        width: 1px;
        height: 1px;
        padding: 0;
        margin: -1px;
        overflow: hidden;
        clip: rect(0,0,0,0);
        border: 0;
    }
    

    In your case you can define for example .accent-color or simply .accent which can turn any element's color into red or whatever :)