Menu Search
Jump to the content X X
Smashing Conf New York

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf New York, dedicated to smart front-end techniques and design patterns.

Battling BEM (Extended Edition): 10 Common Problems And How To Avoid Them

Whether you’ve just discovered BEM or are an old hand (in web terms anyway!), you probably appreciate what a useful methodology it is. If you don’t know what BEM is, I suggest you read about it on the BEM website1 before continuing with this post, because I’ll be using terms that assume a basic understanding of this CSS methodology.

This article aims to be useful for people who are already BEM enthusiasts and wish to use it more effectively or people who are curious to learn more about it.

Further Reading on SmashingMag: Link

Now, I’m under no illusion that this is a beautiful way to name things. It’s absolutely not. One of things that put me off of adopting it for such a long time was how eye-gougingly ugly the syntax is. The designer in me didn’t want my sexy markup cluttered with dirty double-underscores and foul double-hyphens.

The developer in me looked at it pragmatically. And, eventually, the logical, modular way of building a user interface outweighed the right-side of my brain that complained, “But it’s not pretty enough!”. I certainly don’t recommend picking a living-room centrepiece this way, but when you need a life jacket (as you do in a sea of CSS5), I’ll take function over form any day. Anyway, enough rambling. Here are the 10 dilemmas I’ve battled with and some tips on how to deal with them.

1. “What To Do About ‘Grandchild’ Selectors (And Beyond)?” Link

To clarify, you would use a grandchild selector when you need to reference an element that is nested two levels deep. These bad boys are the bane of my life, and I’m sure their misuse is one of the reasons people have an immediate aversion to BEM. I’ll give you an example:

<div class="c-card">

    <div class="c-card__header">
        <!-- Here comes the grandchild… -->
        <h2 class="c-card__header__title">Title text here</h2>
    </div>

    <div class="c-card__body">

        <img class="c-card__body__img" src="some-img.png" alt="description">
        <p class="c-card__body__text">Lorem ipsum dolor sit amet, consectetur</p>
        <p class="c-card__body__text">Adipiscing elit.
            <a href="/somelink.html" class="c-card__body__text__link">Pellentesque amet</a>
        </p>

    </div>
</div>

As you might imagine, naming in this way can quickly get out of hand, and the more nested a component is, the more hideous and unreadable the class names become. I’ve used a short block name of c-card and the short element names of body, text and link, but you can imagine how out of control it gets when the initial block element is named something like c-drop-down-menu.

I believe the double-underscore pattern should appear only once in a selector name. BEM stands for Block__Element--Modifier, not Block__Element__Element--Modifier. So, avoid multiple element level naming. If you’re getting to great-great-great-grandchild levels, then you’ll probably want to revisit your component structure anyway.

BEM naming isn’t strictly tied to the DOM, so it doesn’t matter how many levels deep a descendent element is nested. The naming convention is there to help you identify relationships with the top-level component block — in this case, c-card.

This is how I would treat the same card component:

<div class="c-card">
    <div class="c-card__header">
        <h2 class="c-card__title">Title text here</h2>
    </div>

    <div class="c-card__body">

        <img class="c-card__img" src="some-img.png" alt="description">
        <p class="c-card__text">Lorem ipsum dolor sit amet, consectetur</p>
        <p class="c-card__text">Adipiscing elit.
            <a href="/somelink.html" class="c-card__link">Pellentesque amet</a>
        </p>

    </div>
</div>

This means that all of the descendent elements will be affected only by the card block. So, we would be able to move the text and images into c-card__header or even introduce a new c-card__footer element without breaking the semantic structure.

2. “Should I Be Namespacing?” Link

By now, you’ve probably noticed the use of c- littered throughout my code samples. This stands for “component” and forms the basis of how I namespace my BEM classes. This idea stems from Harry Robert’s namespacing technique6, which improves code readability.

This is the system I have adopted, and many of the prefixes will appear throughout the code samples in this article:

Type Prefix Examples Description
Component c- c-card
c-checklist
Form the backbone of an application and contain all of the cosmetics for a standalone component.
Layout module l- l-grid
l-container
These modules have no cosmetics and are purely used to position c- components and structure an application’s layout.
Helpers h- h-show
h-hide
These utility classes have a single function, often using !important to boost their specificity. (Commonly used for positioning or visibility.)
States is-
has-
is-visible
has-loaded
Indicate different states that a c- component can have. More detail on this concept can be found inside problem 6 below, but
JavaScript hooks js- js-tab-switcher These indicate that JavaScript behavior is attached to a component. No styles should be associated with them; they are purely used to enable easier manipulation with script.

I have found that using these namespaces has made my code infinitely more readable. Even if I don’t manage to sell you on BEM, this is definitely a key takeaway.

You could adopt many other namespaces, like qa- for quality-assurance testing, ss- for server-side hooks, etc. But the list above is a good starting point, and you can introduce others as you get comfortable with the technique.

You’ll see a good example of the utility of this style of namespacing in the next problem.

3. “What Should I Name Wrappers?” Link

Some components require a parent wrapper (or container) that dictates the layout of the children. In these cases, I always try to abstract the layout away into a layout module, such as l-grid, and insert each component as the contents of each l-grid__item.

In our card example, if we wanted to lay out a list of four c-cards, I would use the following markup:

<ul class="l-grid">
    <li class="l-grid__item">
        <div class="c-card">
            <div class="c-card__header">
                […]
            </div>
            <div class="c-card__body">
                […]
            </div>
        </div>
    </li>
    <li class="l-grid__item">
        <div class="c-card">
            <div class="c-card__header">
                […]
            </div>
            <div class="c-card__body">
                […]
            </div>
        </div>
    </li>
    <li class="l-grid__item">
        <div class="c-card">
            <div class="c-card__header">
                […]
            </div>
            <div class="c-card__body">
                […]
            </div>
        </div>
    </li>
    <li class="l-grid__item">
        <div class="c-card">
            <div class="c-card__header">
                […]
            </div>
            <div class="c-card__body">
                […]
            </div>
        </div>
    </li>
</ul>

You should now have a solid idea of how layout modules and component namespaces should play together.

Don’t be afraid to use a little extra markup to save yourself a massive headache. No one is going to pat you on the back for shaving off a couple of <div> tags!

In some instances, this isn’t possible. If, for example, your grid isn’t going to give you the result you want or you simply want something semantic to name a parent element, what should you do? I tend to opt for the word container or list, depending on the scenario. Sticking with our cards example, I might use <div class="l-cards-container">[…]</div> or <ul class="l-cards-list">[…]</ul>, depending on the use case. The key is to be consistent with your naming convention.

4. “Cross-Component… Components?” Link

Another issue commonly faced is a component whose styling or positioning is affected by its parent container. Various solutions to this problem are covered in detail by Simurai7. I’ll just fill you in on what I believe is the most scalable approach.

To summarize, let’s assume we want to add a c-button into the card__body of our previous example. The button is already its own component and is marked up like this:

<button class="c-button c-button--primary">Click me!</button>

If there are no styling differences in the regular button component, then there is no problem. We would just drop it in like so:

<div class="c-card">
    <div class="c-card__header">
        <h2 class="c-card__title">Title text here</h3>
    </div>

    <div class="c-card__body">

        <img class="c-card__img" src="some-img.png">
        <p class="c-card__text">Lorem ipsum dolor sit amet, consectetur</p>
        <p class="c-card__text">Adipiscing elit. Pellentesque.</p>

        <!-- Our nested button component -->
        <button class="c-button c-button--primary">Click me!</button>

    </div>
</div>

However, what happens when there are a few subtle styling differences — for example, we want to make it a bit smaller, with fully rounded corners, but only when it’s a part of a c-card component?

Previously, I stated that I find a cross-component class to be the most robust solution:

<div class="c-card">
    <div class="c-card__header">
        <h2 class="c-card__title">Title text here</h3>
    </div>

    <div class="c-card__body">

        <img class="c-card__img" src="some-img.png">
        <p class="c-card__text">Lorem ipsum dolor sit amet, consectetur</p>
        <p class="c-card__text">Adipiscing elit. Pellentesque.</p>

        <!-- My *old* cross-component approach -->
        <button class="c-button c-card__c-button">Click me!</button>

    </div>
</div>

This is what is known on the BEM website8 as a “mix.” I have, however, changed my stance on this approach, following some great comments from Esteban Lussich.

In the example above, the c-card__c-button class is trying to modify one or more existing properties of c-button, but it will depend on the source order (or even specificity) in order to successfully apply them. The c-card__c-button class will work only if it is declared after the c-button block in the source code, which could quickly get out of hand as you build more of these cross-components. (Whacking on an !important is, of course, an option, but I certainly wouldn’t encourage it!)

The cosmetics of a truly modular UI element should be totally agnostic of the element’s parent container — it should look the same regardless of where you drop it. Adding a class from another component for bespoke styling, as the “mix” approach does, violates the open/closed9 principle of component-driven design — i.e there should be no dependency on another module for aesthetics.

Your best bet is to use a modifier for these small cosmetic differences, because you may well find that you wish to reuse them elsewhere as your project grows.

<button class="c-button c-button--rounded c-button--small">Click me!</button>

Even if you never use those additional classes again, at least you won’t be tied to the parent container, specificity or source order to apply the modifications.

Of course, the other option is to go back to your designer and tell them that the button should be consistent with the rest of the buttons on the website and to avoid this issue altogether… but that’s one for another day.

5. “Modifier Or New Component?” Link

This is one of the biggest problems is deciding where a component ends and a new one begins. In the c-card example, you might later create another component named c-panel with very similar styling attributes but a few noticeable differences.

But what determines whether there should be two components, c-panel and c-card, or simply a modifier for c-card that applies the unique styles.

It’s very easy to over-modularize and make everything a component. I recommend starting with modifiers, but if you find that your specific component CSS file is getting difficult to manage, then it’s probably time to break out a few of those modifiers. A good indicator is when you find yourself having to reset all of the “block” CSS in order to style your new modifier — this, to me, suggests new component time.

The best way, if you work with other developers or designers, is to ask them for an opinion. Grab them for a couple of minutes and discuss it. I know this answer is a bit of a cop-out, but for a large application, it’s vital that you all understand what modules are available and agree on exactly what constitutes a component.

6. “How To Handle States?” Link

This is a common problem, particularly when you’re styling a component in an active or open state. Let’s say our cards have an active state; so, when clicked on, they stand out with a nice border styling treatment. How do you go about naming that class?

The way I see it, you have two options really: either a standalone state hook or a BEM-like naming modifier at the component level:

<!-- standalone state hook -->
<div class="c-card is-active">
    […]
</div>

<!-- or BEM modifier -->
<div class="c-card c-card--is-active">
    […]
</div>

While I like the idea of keeping the BEM-like naming for consistency, the advantage of the standalone class is that it makes it easy to use JavaScript to apply generic state hooks to any component. When you have to apply specific modifier-based state classes with script, this becomes more problematic. It is, of course, entirely possible, but it means writing a lot more JavaScript10 for each possibility.

Sticking to a standard set of state hooks makes sense. Chris Pearce has compiled a good list11, so I recommend just pinching those.

7. “When Is It OK Not To Add A Class To An Element?” Link

I can understand people being overwhelmed by the sheer number of classes required to build a complex piece of UI, especially if they’re not used to assigning a class to every tag.

Typically, I will attach classes to anything that needs to be styled differently in the context of the component. I will often leave p tags classless, unless the component requires them to look unique in that context.

Granted, this could mean your markup will contain a lot of classes. Ultimately, though, your components will be able to live independently and be dropped anywhere without a risk of side effects.

Due to the global nature of CSS, putting a class on everything gives us control over exactly how our components render. The initial mental discomfort caused is well worth the benefits of a fully modular system.

8. “How To Nest Components?” Link

Suppose we want to display a checklist in our c-card component. Here is a demonstation of how not to mark this up:

<div class="c-card">
    <div class="c-card__header">
        <h2 class="c-card__title">Title text here</h3>
    </div>

    <div class="c-card__body">

        <p>I would like to buy:</p>

        <!-- Uh oh! A nested component -->
        <ul class="c-card__checklist">
            <li class="c-card__checklist__item">
                <input id="option_1" type="checkbox" name="checkbox" class="c-card__checklist__input">
                <label for="option_1" class="c-card__checklist__label">Apples</label>
            </li>
            <li class="c-card__checklist__item">
                <input id="option_2" type="checkbox" name="checkbox" class="c-card__checklist__input">
                <label for="option_2" class="c-card__checklist__label">Pears</label>
            </li>
        </ul>

    </div>
    <!-- .c-card__body -->
</div>
<!-- .c-card -->

We have a couple of problems here. One is the grandparent selector that we covered in section 1. The second is that all of the styles applied to c-card__checklist__item are scoped to this specific use case and won’t be reusable.

My preference here would be to break out the list itself into a layout module and the checklist items into their own components, enabling them to be used independently elsewhere. This brings our l- namespacing back into play as well:

<div class="c-card">
    <div class="c-card__header">
        <h2 class="c-card__title">Title text here</h3>
    </div>

    <div class="c-card__body"><div class="c-card__body">

        <p>I would like to buy:</p>

        <!-- Much nicer - a layout module -->
        <ul class="l-list">
            <li class="l-list__item">

                <!-- A reusable nested component -->
                <div class="c-checkbox">
                    <input id="option_1" type="checkbox" name="checkbox" class="c-checkbox__input">
                    <label for="option_1" class="c-checkbox__label">Apples</label>
                </div>

            </li>
            <li class="l-list__item">

                <div class="c-checkbox">
                    <input id="option_2" type="checkbox" name="checkbox" class="c-checkbox__input">
                    <label for="option_2" class="c-checkbox__label">Pears</label>
                </div>

            </li>
        </ul>
        <!-- .l-list -->

    </div>
    <!-- .c-card__body -->
</div>
<!-- .c-card -->

This saves you from having to repeat the styles, and it means we can use both the l-list and c-checkbox in other areas of our application. It does mean a little more markup, but it’s a small price to pay for readability, encapsulation and reusability. You’ve probably noticed these are common themes!

9. “Won’t Components End Up With A Million Classes?” Link

Some argue that having a lot of classes per element is not great, and --modifiers can certainly add up. Personally, I don’t find this to be problematic, because it means the code is more readable and I know exactly what it is supposed to be doing.

For context, this is an example of four classes being needed to style a button:

<button class="c-button c-button--primary c-button--huge  is-active">Click me!</button>

I get that this syntax is not the prettiest to gaze upon, but it is explicit.

However, if this is giving you a major headache, you could look at the extension technique12 that Sergey Zarouski came up with. Essentially, we would use .className [class^="className"], [class*=" className"] in the style sheet to emulate extension functionality in vanilla CSS. If this syntax looks familiar to you, that’s because it is very similar to the way Icomoon13 handles its icon selectors.

With this technique, your output might look something like this:

<button class="c-button--primary-huge  is-active">Click me!</button>

I don’t know whether the performance hit of using the class^= and class*= selectors is much greater than using individual classes at scale, but in theory this is a cool alternative. I’m fine with the multi-class option myself, but I thought this deserved a mention for those who prefer an alternative.

10. “Can We Change A Component’s Type Responsively?” Link

This was a problem posed to me by Arie Thulank and is one for which I struggled to come up with a 100% concrete solution.

An example of this might be a dropdown menu that converts to a set of tabs at a given breakpoint, or offscreen navigation that switches to a menu bar at a given breakpoint.

Essentially, one component would have two very different cosmetic treatments, dictated by a media query.

My inclination for these two particular examples is just to build a c-navigation component, because at both breakpoints this is essentially what it is doing. But it got me thinking, what about a list of images that converts to a carousel on bigger screens? This seems like an edge case to me, and as long as it is well documented and commented, I think it is perfectly reasonable to create a one-off standalone component for this type of UI, with explicit naming (like c-image-list-to-carousel).

Harry Roberts has written about responsive suffixes14, which is one way to handle this. His approach is intended more for changes in layout and print styles, rather than shifts of entire components, but I don’t see why the technique couldn’t be applied here. So, essentially you would author classes like this:

<ul class="c-image-list@small-screen c-carousel@large-screen">

These would then live in your media queries for the respective screen sizes. Pro tip: You have to escape the @ sign in your CSS with a backslash, like so:

.c-image-list\@small-screen {
    /* styles here */
}

I haven’t had much cause to create these type of components, but this feels like a very developer-friendly way to do it, if you have to. The next person coming in should be able to easily understand your intention. I’m not advocating for names like small-screen and large-screen — they are used here purely for readability.

Summary Link

BEM has been an absolute lifesaver for me in my effort to create applications in a modular, component-driven way. I’ve been using it for nearly three years now, and the problems above are the few stumbling blocks I’ve hit along the way. I hope you’ve found this article useful, and if you’ve not given BEM a go yet, I highly encourage you to do so.

Note: This is an enhanced version of my original article “Battling BEM: 5 Common Problems and How to Avoid Them15,” which appeared on Medium. I’ve added five more common problems, (some of which were asked about in the comments of that article) and I have altered my views on one of the original problems.

(vf, al, il)

Footnotes Link

  1. 1 https://en.bem.info/
  2. 2 https://www.smashingmagazine.com/2012/04/a-new-front-end-methodology-bem/
  3. 3 https://www.smashingmagazine.com/2014/07/bem-methodology-for-small-projects/
  4. 4 https://www.smashingmagazine.com/2013/02/the-history-of-the-bem-methodology/
  5. 5 https://www.smashingmagazine.com/tag/css
  6. 6 http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/
  7. 7 http://simurai.com/blog/2015/05/11/nesting-components
  8. 8 https://en.bem.info/forum/4/
  9. 9 https://en.wikipedia.org/wiki/Open/closed_principle
  10. 10 https://www.smashingmagazine.com/tag/javascript
  11. 11 https://github.com/chris-pearce/css-guidelines#state-hooks
  12. 12 http://webuniverse.io/css-organization-naming-conventions-and-safe-extend-without-preprocessors/#To_extend_or_not_to_extend?
  13. 13 https://icomoon.io/
  14. 14 http://csswizardry.com/2015/08/bemit-taking-the-bem-naming-convention-a-step-further/
  15. 15 https://medium.com/fed-or-dead/battling-bem-5-common-problems-and-how-to-avoid-them-5bbd23dee319#.xbw2qszc1

↑ Back to top Tweet itShare on Facebook

David is a front-end developer from the UK who has been coding since 1998 when spacer gifs and blink tags were still a thing. He is a writer, speaker and coder who is passionate about moving the web forward. You can find his ramblings about this (and all things front-end) at Fed || Dead.

  1. 1

    Aleks Hudochenkov

    June 1, 2016 5:28 pm

    Great article! Thank you!

    About 9th question. This code is not a BEM:

    Click me!

    “In the BEM methodology, a modifier cannot be used outside of the context of its owner”, official documentation says.

    This is correct:

    Click me!

    1
    • 2

      Aleks Hudochenkov

      June 1, 2016 5:31 pm

      Sorry, about wrong markup :)

      Great article! Thank you!

      About 9th question. This code is not a BEM:

      <button class="c-button--primary-huge is-active">Click me!</button>

      “In the BEM methodology, a modifier cannot be used outside of the context of its owner”, official documentation says.

      This is correct:

      <button class="c-button c-button--primary-huge is-active">Click me!</button>

      17
      • 3

        Correct, this approach is new and seems to be working well / doesn’t really have negative side effects.

        0
  2. 4

    Adam van den Hoven

    June 1, 2016 6:19 pm

    One of your problems with any structured system such as BEM is that you naturally set too many properties, almost always shortcuts (background being the most frequent source of problems). If you’re careful to only set those properties you care about (background-color:#ff00ff; instead of background:#ff00ff;) you will have fewer conflicts to deal with.

    Also, once CSS Variables become widely available a lot of the complexity outlined can go away:

    :root { 
    --button-bg-color: #ff00ff;
    }
    .c-card {
    --button-bg-color: #ff0000;
    }
    .c-button{
    background-color: var(--button-bg-color);
    }
    
    0
  3. 5

    I think you’ve missed the point about using namespaces. When you boil it down to simply layout and component, the name-spacing is no longer useful and becomes noise. Harry Robert’s technique creates an understanding between what classes are for theming, scoping, or object-orientation.

    Text

    He’s using the context of o, s, c, and t to understand how the classes interact with each other.

    You don’t have that context when you combine them all into c, and then rely heavily on BEM to achieve that same meaning.

    Anybody looking at that code should be able to understand that grid and grid__item are layout related pieces of content. The cs and ls just get in the way, in my opinion. There are two many things namespaced with the same letter to provide any useful meaning.

    If, perhaps, you had a layout class that wasn’t as obvious, I could understand the need to add some more context as to what’s happening. I’d be okay to see limited use of hero-layout then I would to have to train my eye to see past the noise of everything saying l-hero c-headline c-banner c-image c-footer c-link.

    3
  4. 9

    Jason Morehead

    June 1, 2016 7:27 pm

    Re. “grandchild” selectors, I’ve taken a slightly different approach. Consider your initial example:

    Title text here

    Since the “c-card__header” element has a child — the H2 tag — I’d make it a parent element, like so:

    Title text here

    Thus creating a new BEM block.

    This seems a bit more accurate than your approach — i.e., having “c-card__header” and “c-card__title” elements — because “c-card__title” isn’t a direct descendant of the “c-card” element. And I’ve always understood that ideally, double underscores imply immediate childhood, not any level of descendance.

    I realize my approach isn’t perfect in all situations, and it may not be keeping entirely in-line with BEM principles. However, I’ve found that it helps keep things a bit more modular and self-contained by limiting the scope of element relationships.

    -1
  5. 12

    And that, kids, is a perfect example why BEM should have never existed at all.

    -61
    • 13

      That’s simply what happens with people who can’t evolve. They had the freaking problems with standard CSS, but common, It’s 2016 and we have preprocessors for more than 10 years. Why would you completely give up the readability of your markup to solve problems that don’t even exist today. BEM was solving cr4p from plain olf CSS, but all it solves is no longer an issue thanks to css preprocessors. While our tools evolved, our friends didn’t. They are still banging their heads against the wall to solve problems which don’t exist in today’s dev world.

      So guys, continue to create modifiers like “card–white” and give up on all separation of concerns, while you could freakingly keep the color sh*t in the styling logic. You could as well return to inline styling.

      If you really think stuff like “specificity” is a problem then you should really give up writing CSS, ’cause you dont really understand it, and it’s not for you.

      F**K BEM, make HTML & CSS great again.

      -33
  6. 14

    How do you best ensure that your typography stays consistent? Do you create components specifically for different forms of typography ui?

    0
    • 15

      I usually set defaults for the heading-elements and then have some utility-classes like ‘u-heading-alpha’, ‘u-heading-beta’ to overwrite the default behaviour. All set in REM’s ofcourse.

      0
      • 16

        In some cases a title should be a h1 for semantic reasons but somehow the designer styled it like a h2. Now you would need to have a utility class with the same styling as h1 which is not very practical. Therefore I never style any heading element. Instead I create classes like .t-h1, .t-h2, .t-page-title etc. (namespacing t- for typography) and then apply them to the elements like h1.t-h2 or h1.t-page-title.
        Another advantage of this is that you can use your typo-classes on any tags and you’re note bound the the h-tags. And you have all you typo together in one place and not scattered over x components. Here’s an example: http://pastebin.com/J0XKp9nF

        4
  7. 17

    For #7, another approach is to delegate state as much as possible to aria attributes, and style based on [aria-state=”whatever”]. This helps bake accessibility into component behaviour from the start, and gives you a single source of truth (ie – if a component is active as far as style is concerned, it’s also active as far as screenreaders are concerned). The JS needed to change state should get simpler too!

    0
  8. 18

    I’ve never worked in big projects or teams where, I guess, BEM would reach its full potential, but I’m still struggling to understand the concept. To me it seems like it gets rid of the C in CSS and I don’t really understand the benefit. Also, any BEM markup looks like to many classes to me.

    This is obviously a matter of personal taste. I’m not saying that BEM is bad or wrong, it just doesn’t work for me.

    2
    • 19

      I think the minds behind BEM would agree about losing the “C”. The problem BEM (and OOCSS) were designed to solve was that the cascade is too hard to understand, and is too brittle. Yes, you end up using more classes, but reading a lot of class names has less cognitive overhead that trying to understand the styling of an element based on its context.

      3
      • 20

        That’s exactly my point. BEM doesn’t remove cascading and its potential problems, it replaces it with another system and other potential problems (the whole article is about some of those problems). If we opt to use BEM we’ll have to understand both of these systems, because we can’t just pretend that cascading doesn’t exist.

        1
  9. 21

    René Stalder

    June 2, 2016 9:38 am

    Is it semantically correct to use l-layout classes? At some point, I’ve got used to have a layout.css where I place my components on the body. What I’m doing there is, I summary different selectors, e.g I have a component for a list of persons and one for a list of companies, but both should arranged in a grid like layout, I apply this to my layout.css:

    .personlist,
    .companylist { 
      /* Layout Properties */
    }

    At the end, I control the layout with changes in CSS instead of changing selectors in the HTML. Except the design is user controlled, for example by CMS parameters.

    0
  10. 22

    Marcin Goscicki

    June 2, 2016 9:41 am

    About 7. question – “When Is It OK Not To Add A Class To An Element?”.

    What if our

    .c-card__body

    is filled with data from WYSIWYG text editor? Is it fine then to style

    .c-card__body p
    , etc. or you suggest another approach?
    3
    • 23

      Alastair Hodgson

      June 2, 2016 3:05 pm

      This is the rare case in which I will use element selectors too :D

      0
    • 24

      In this case I would create a component called c-WYSIWYG and then scope all HTML selectors inside this class, like:

      .c-wysiwyg {
          p {
              padding-bottom: 20px;    
          }
          table {
              background: grey;
          }
          ...
      }
      
      3
    • 25

      As Ben mentions, usually in projects I’m handing over front-end component code to backend developers, and they’re integrating it into a CMS. In any instance where a client might be adding rich text content, a separate component gets added, and I can target its dynamic content like paragraph tags, etc. in a single area of my styles.

      0
  11. 26

    Jérémie Fontaine

    June 2, 2016 11:09 am

    I found this article very useful!
    About those selectors in 9th question, shouldn’t we stick to what Sergey Zarouski came up with? By adding two dashes to avoid styling elements like so :

    .className [class^="className--"], [class*=" className--"]
    1
    • 27

      Jérémie Fontaine

      June 2, 2016 11:12 am

      Also a comma is needed :

      .className, [class^="className--"], [class*=" className--"]
      0
      • 28

        Juraj Bachleda

        June 2, 2016 6:07 pm

        I preffer not to use this approach at all. If you have each button–active & button–big & button–rounded class applied to element, you repeat the base three times then. If you make a single class for that, you miss a modularity. I’d say nope for this.

        0
        • 29

          Jérémie Fontaine

          June 3, 2016 10:41 am

          Misconception here. Everything is kept modular!
          Instead of writing :
          icon icon--big icon--blue
          This code allow you to just write :
          icon--big--blue
          Its still modular, you just gain compactness.

          1
  12. 30

    Excellent article! I’ve ran into many of these situations and come to mostly the same conclusions on my own. It’s nice to feel validated in my decisions, lol.

    6
  13. 31

    Julián Landerreche

    June 3, 2016 3:03 am

    Currently, I’m using a CamelCase syntax without any kind of prefixing.
    For example:

    
    .FeaturedProduct { // Block: .FeaturedProduct
    
      &--onSale { // Modifier: .FeaturedProduct--onSale
        ...	
      }    
    
      &-header {  
      // Element: .FeaturedProduct-header
        ...
      }
    
      &-img {  
      // Element: .FeaturedProduct-img
        ...
      }
    
      &Wrapper { 
      // Block: .FeaturedProductWrapper.  This is a block (usually without any elements belonging to it) that wraps the .FeaturedProductBlock. It's just a wrapper, for when you need it.
        ...
      }
    
    }
    

    (and in a pastebin, just in case this gets mangled)

    Also, if, on a block, an element has also its own related elements, I tend to do this, for example

    
    .Article { // Block: .Article
    
      &-aside { // Element: .Article-aside
        ...
        &Header { // Element: .Article-asideHeader
           ...
        }
        &Body { // Element: .Article-asideBody
           ...
        }
      }
    }
    

    (another pastebin, just in case)

    This way, I can create more granular elements without the need to resort to new blocks and without making the syntax any more complex.

    1
  14. 32

    Just use SASS. And give up on BEM, it’s not really solving any problem if you understand SASS.

    You also should use the dev tools to understand the styling of an element from its context, ’cause it’s 2016 and we can.

    Make CSS great again!

    -14
    • 33

      @Otr SASS is a tool, BEM is an architecture. They solve different problems.

      For small sites, yeah, BEM may be overkill. But for large CSS codebases used by multiple developers, BEM is the best way I’ve found to write stable, reusable styles.

      If you disagree, check out https://en.bem.info/methodology/solved-problems/ and explain how SASS solves those problems (especially #1 and #3).

      7
      • 34

        @Zac, Otr’s is correct, and it is a scripting language not a tool. Take for instance SASS; This not only organizes your code, but organizes it in a way that makes it expandable. BEM does not. You are fortifying your HTML in a way that makes adjusting styling difficult. You are almost forcing yourself into !important tags.

        BEM becomes particularly harmful when you start needing unique identifiers because the class names become convoluted. I won’t even get started on the painstaking task of DOM manipulation with a BEM project. I’ve had to tolerate 3 already.

        If you really are looking to use re-usable code I strongly encourage looking into SASS because it does allow of basic CSS, but better.

        For your #1 & #3 question this is a re-write in sass. (Parents are the identifiers as Sass will take care of the rest)

        SASS:
        .c-card{
        .header{
        .title{

        }
        }
        .body{
        img{

        }
        p{

        }
        a{

        }
        }
        }

        You’ll notice #3 that you don’t need to worry about

        CSS OUTPUT:
        when the preprocceses it will output into a .css format like this. Not only this will carry over any default classes you would have (example for .title), but allows for a clean and easy overwrite because what is below is a unique identifier with c-card.
        .c-card {}
        .c-card .header{}
        .c-card .header .title{}
        .c-card .body {}
        .c-card .body .img{}
        .c-card .body .p{}
        .c-card .body .a{}

        The above is just a sliver of what SASS can truly do.

        -4
        • 35

          May Help with some indentation :)

          .c-card{
          	.c-card-header{
          		.title{
          
          		}
          	}
          	.c-card-body{
          		img{
          
          		}
          		p{
          
          		}
          		a{
          
          		}
          	}
          }
          
          0
        • 36

          Your sass example looks like a maintenance nightmare.

          What happens when some other developer comes in and adds
          .c-card .title { color: blue; } but you didn’t originally set the color in .c-card .header .title ?

          suddenly you don’t have a good way to understand how one change may effect others because of nesting. Any sufficiently large css base can get out of hand quickly.

          Many in the Sass world suggest that you avoid nesting selectors http://thesassway.com/intermediate/avoid-nested-selectors-for-more-modular-css

          I would highly agree, but once you’re not nesting selectors you need a more sane way to name your selectors. That’s where BEM steps in. I would also suggest not to use SASS to do BEM &__element is a bad idea. impossible to search for.

          8
          • 37

            Michael Maaß

            June 16, 2016 3:38 pm

            Yes, when you decide to use & in Less or Sass you can’t search the complete class name.

            BUT

            With the clean architecture of BEM and its components you don’t HAVE to search. If you come along a class with the name ‘gallery__header–emphasized’ you should find everything you need in **/*gallery.scss. If you must you can search `header` in there…

            7
  15. 38

    Unfortunately with our situation the design has changed so many times over the course of development that we are starting to come up with names like:

    o-conversation-search-list__nested-list-item–with-icon

    and the style that is attached to that ridiculous class name?

    padding-left: 15px

    BEM was great at first but it’s also quickly spiralling out of control. I think the good side to it is that when it comes time to refactor (which will undoubtedly happen once the powers that be finally catch a wake-up) we can at least have a pretty good overview of just how badly things are overnested and with pretty much zero re-usable components.

    2
  16. 39

    #9 directly contradicts BEM’s methodology which is exactly why it is more harmful than good in many cases. You are restricting your code in a manor that if handed to a person new to the project would require them to piece together your code. On top of that any site that uses a JS Framework or is dynamic heavy a class name like this would be incredibly unhelpful.
    class=”c-button c-button–primary c-button–huge is-active”

    BEM is working backwards, and if you are not on a solo project. Do NOT use BEM. You are basically building a prison around your code & I already know agency’s at least where I am at push back on this methodology.

    Preprocessors do exactly what BEM is trying to solve for.

    -6
  17. 40

    Esteban Lussich

    June 8, 2016 6:02 am

    Thanks for the shout-out!
    Nice reading, as usual, and good food for thought.

    0
  18. 41

    From the comments, I see there’s still a lot of misunderstanding about BEM and why it can be a useful solution. I guess everybody has to experience the “aha!” moment themselves as soon as they work on something with a very large scale, an old code base, or a team of dozens of developers.

    Anyway, a great article that touches a lot of pragmatic aspects of BEM. I’m in particular opinionated about #4 in the list. If your designer frequently comes to you with design variations where elements look just slightly different in different context, it’s not a problem to be solved in BEM. It means the design is arbitrary and does not follow the design language, or there is no design language.

    It’s a sign of design and dev not working together correctly, which should be solved at the people level, not the code level.

    6
  19. 42

    Vicente Sarmento

    June 9, 2016 5:40 pm

    I have just found out that many “solutions” that I created in the projects I work in are the same you wrote here. Sweet. :)

    Thanks for sharing. This article is a must read.

    1
  20. 43

    Fantastic article, thank you. I am a big fan of BEM and it is helpful to be able to link to resources like this to encourage others to follow suit.

    I also wrote an article about Point 4 – I tend to use a mixture of modifiers and context wrappers to avoid ‘component collide’:
    http://iamkeir.com/post/124059685310/styling-components-within-components

    0
  21. 44

    First of all: Thank you very much for this article. It’s just brilliant.

    I have a question:
    Many times I need something like this

    
    some-text {
        text-align: right
    }
    

    E.g. a copyright in the footer.
    Is this a component?
    so with bem I will use the class name:

    .c-copyright-footer{}

    0
  22. 45

    It seems that the best way to use BEM without the visual ugliness it creates due to the long class names it creates, is to try to minimize that by coming up with ultra-short yet meaningful class names. For instance instead of

    ....block--large__content__meta--price

    it could be

    ....box--big__data__meta--cost

    Not much, but still a slight difference.

    0
  23. 46

    Awesome article! Thanks.

    0

↑ Back to top