cssbem

Change hyperlink colour with BEM


I am trying BEM for the first time today.

Why is my link colour not different from the default?

It really should be yellow, right?

.nav-primary {

  &__menu {
    color:red;
    }
    
  &__menuitem {
      color:green;
    }
    
  &__menuitem a {
      color:yellow;
    }      

  }
<div class="nav-primary">
    <ul>
        <li><a href="">why am I not a different colour?</a></li>
    </ul>
</div>


Solution

  • You're targeting different elements ie.

    .nav-primary {
    
      &__menu {
        color:red;
        }
    
      &__menuitem {
          color:green;
        }
    
      &__menuitem a {
          color:yellow;
        }      
      }   
    

    will compile to:

    .nav-primary__menu { color: red; }   
    .nav-primary__menuitem { color: green; }
    .nav-primary__menuitem a { color:yellow; } 
    

    which doesn't correspond to any elements in your html.

    I guess you need to add nav-primary__menuitem class to your "element", which in your case would be a list item, as so:

    <div class="nav-primary">
        <ul>
            <li class="nav-primary__menuitem"><a href="">why am I not a different colour?</a></li>
        </ul>
    </div>   
    

    Only then your last rule will apply to your link.

    But to BEM-ify your code, you need to decide what is the Block, and what is an Element of this block in your html structure. So in your code you'd likely want to also add a class to your link element. Providing that you want your block to be a nav-primary element, use ie .nav-primary__menulink class on a link too:

    then your CSS/SASS/LESS will look:

    .nav-primary {
    
          &__menu {
            color:red;
            }
    
          &__menuitem {
              color:green;
            }
    
          &__menulink {
              color:yellow;
            }      
          }