-
-
Save tvandervossen/50897e4c0ad40b162b033da1f17b7867 to your computer and use it in GitHub Desktop.
| 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> |
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.
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.