Search code examples
cssnaming-conventionssemanticsbem

BEM class chainability


I've recently played around BEM syntax, And I was wondering about the use of chainability in CSS, as I try to use the class=*^ & class=* selector in order to obtain a more free CSS class order.

eg:

[class^="btn"][class*="--default"][class*="--outline"] {/* style */}

So that

<button class="btn--default--outline">Button</button>

or

<button class="btn--outline--default">Button</button>

would be similar.

And what would be more readable than:

<button class="btn btn--default btn--outline">Button</button>

This guy is using the same concept but everybody seems to disagree while not advancing real source for their argument (slow? anti-html conform? anti-semantic?).

So is there reasons not to use this syntax?


Solution

  • You should avoid your technique because attribute selectors are slower than class selectors. And also, I suspect that the attribute selectors with "^=" or "*=" can not be performant on huge DOM, in the same way that a "LIKE" in SQL is not as effective as a "=" on an indexed column. (And strange ways are always more difficult to write and to maintain).

    I suggest this BEM syntax:

    • BlockName
    • BlockName.-modifierName
    • BlockName-elementName
    • BlockName-elementName.-modifierName

    With this syntax, your example becomes:

    <button class="Btn -default -outline">Button</button>
    

    NB: Modifiers should not be styled independently of their block or element, because this practice would not been conform to the BEM methodology. If -outline is a transversal class, make it a block:

    <button class="Btn -default Outline">Button</button>