Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/50897e4c0ad40b162b033da1f17b7867 to your computer and use it in GitHub Desktop.
Save tvandervossen/50897e4c0ad40b162b033da1f17b7867 to your computer and use it in GitHub Desktop.
Trying to understand the motivation behind the BEM class naming convention
In https://css-tricks.com/bem-101/ the following CSS is given as an exampke:
/* Block component */
.btn {}
/* Element that depends upon the block */
.btn__price {}
/* Modifier that changes the style of the block */
.btn--orange {}
.btn--big {}
This CSS is used to style the following HTML:
<a class="btn btn--big btn--orange" href="http://css-tricks.com">
<span class="btn__price">$9.99</span>
<span class="btn__text">Subscribe</span>
</a>
Why is this better than the following CSS?
/* Block component */
.button {}
/* Element that depends upon the block */
.button .price {}
/* Modifier that changes the style of the block */
.button.orange {}
.button.big {}
With the following HTML?
<a class="button big orange" href="http://css-tricks.com">
<span class="price">$9.99</span>
<span class="text">Subscribe</span>
</a>
@ilyasotkov
Copy link

This should help: https://cssguidelin.es/#naming-conventions-in-html

The reasoning behind BEM, I believe, is that it allows us to clearly see all parent-child (block-element) and element-modifier relationships.

@tijn
Copy link

tijn commented Mar 10, 2018

It is not better per se; it is just name-spacing and it is a tool you can use to add structure to your code so you can reason about it more easily.

Maybe an example makes it more clear how it could benefit you:
Say you would like to style .button.orange .text. To do so you have to know which CSS rules have already been defined for .text since you may want to reset them. If you would have put the button in a header in an aside you would also have to reset .header .text, .aside .text and .aside .header .text. BEM solves this by assuming that this text you have here is actually not really like the other text-classes you might have defined; it's really the button-text. I'd imagine that the top level text class could be used for copy (the text of a story) which, if you think about it, is really different from the text on your button.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment