Created
March 10, 2018 18:02
-
-
Save tvandervossen/50897e4c0ad40b162b033da1f17b7867 to your computer and use it in GitHub Desktop.
Trying to understand the motivation behind the BEM class naming convention
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aheader
in anaside
you would also have to reset.header .text
,.aside .text
and.aside .header .text
. BEM solves this by assuming that thistext
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 leveltext
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.