How to specify state with BEM?

2019-07-27 08:33发布

问题:

Using BEM CSS class syntax, lets say I have an element with the following class:

...
<div class="purchase__module2__heading__tooltip">...</div>
...

Now lets say there is an event or something where this "tooltip" becomes active or visible. What is the proper way to express this with BEM? Do I replace the current class so now it becomes:

...
<div class="purchase__module2__heading__tooltip--active">...</div>
...

or do I add it

...
<div class="purchase__module2__heading__tooltip purchase__module2__heading__tooltip--active">...</div>
...

Or can I just do something simple like this:

...
<div class="purchase__module2__heading__tooltip active">...</div>
...

I think the answer is #2, but it seems very drawn out. #3 is nice and simple but I can't tell if this follows proper BEM guidelines or not.

回答1:

If you're modifying a block or element you must include the base class as well.

For example

<div class="block">
  <div class="block__element">...</div>
</div>

could have the block modified as:

<div class="block block--modifier">
  <div class="block__element block--modifier__element">...</div>
</div>

or the element modified as:

<div class="block">
  <div class="block__element block__element--modifier">...</div>
</div>

In either case you start needing to use multiple classes.


Looking over your example of:

<div class="purchase__module2__heading__tooltip">

It's clear that you're nesting too deeply, preventing yourself from being able to reuse the majority of your code.

Given the names you're using, I'd guess that what you actually have is:

  • a purchase module (.purchase-module)
    • with a heading (.purchase-module__heading)
  • a tooltip (.tooltip)

The markup could look something like:

<article class="purchase-module">
  <h1 class="purchase-module__heading">
    ...heading text...
    <span class="tooltip">...</span>
  </h1>
</article>

Note how making the tooltip active now just requires changing a short class:

<span class="tooltip tooltip--active">...</span>

That's the ideal with BEM.



回答2:

You are right and the answer is #2.

Here's why:

  • https://en.bem.info/methodology/faq/#why-include-the-block-name-in-names-of-modifier-and-element
  • https://en.bem.info/methodology/faq/#how-do-i-make-global-modifiers-for-blocks

BTW, you shouldn't keep DOM structure in naming. And here's why: https://en.bem.info/methodology/faq/#why-does-bem-not-recommend-using-elements-within-elements-block__elem1__elem2



标签: html css bem