Pleasant BEM
Revision of November 28, 2024Pleasant BEM is an alternative BEM syntax, inspired from Nicolas Gallagher's work. The syntax is fully BEM compliant. BEM naming conventions can be learned here.
Syntax
.BlockName
.BlockName.modifierName
.BlockName-elementName
.BlockName-elementName.modifierName
Except for… 1/ DOM children selectors
Note: This rule does not conform to BEM principles. In using it, some of CSS classes are tied to HTML tags. But scalability, with the ability to nest subblocks, is preserved.
The CSS class of a child element can sometimes be omitted.
It is relevant in particular (but not only) when child elements are predetermined by the semantic: <dd>
, <dt>
, <li>
, <td>
, etc. Or when children are positioned through a parent CSS property like display: flex
.
<aside class="TitledList"> <h1 class="TitledList-h1">Fruits</h1> <ul class="TitledList-ul"> <li>Mangoes</li> <li class="highlight">Bananas</li> <li>Pineapples</li> </ul> </aside>
In the CSS code, use the child selector:
.TitledList { &-ul > li { background-color: #ccc; &.highlight { font-weight: bold; } } }
Except for… 2/ Formatted text
Note: This rule does not conform to BEM conventions. The limitation is that only "text format resistant" BEM blocks can be nested in a formatted text.
It's fine to use a "pseudo BEM block" for formatted text, for example: .TextBlock
or .Text
. Style its contents using cascading and inheritance:
.Text, .TextBlock { hyphens: auto; overflow-wrap: break-word; em, i { font-style: italic; } strong, b { font-weight: bold; } } .TextBlock { p, ul, ol { margin-bottom: .65em; } }
Do not use any styles that would apply to the container box (do not use background
, border
, display
, flex
, grid
, margin
, padding
, position
, etc. on .Text
). Instead, use this block in association with other CSS classes responsible for styling the box:
<article class="Post"> <h1 class="Post-h1 Text">Here a <em>formatted title</em></h1> <div class="Post-body TextBlock"> <p>Some <strong>formatted text</strong>.</p> </div> </article>
Set the rules for the .Text
selector at the beginning of the CSS file. Then, a variant can be implemented by styling an associated CSS class (.Post-h1
could define its own font size) or with a modifier.
Except for… 3/ Transversal modifiers
Note: This rule does not conform to BEM conventions.
Prefix with an underscore a CSS class that can affect every sub-block. For example:
._home { .PageTitle { /* something specific to the home page here */ } .Post-h1 { /* something else specific too */ } }
Note – CSS classes outside BEM
When a CSS class is needed outside the scope of BEM, it may have a prefix beginning with a lowercase letter and including a hyphen: .js-searchInput
.