Unifx Unifx - 25 days ago 13
Sass (Sass) Question

SCSS and BEM naming structures and best practices.

At the moment with scss I understand variables, includes and nesting.

I am trying to create a new scss set up that uses the BEM naming structure. so for instance

.btn {
padding: 20px;
.btn__value {
color: $valColour;
}
}

.btn--gold {
color: $gold;
}


So I have the class .btn__value nested as it will be a span inside of the button block and only used there and it depends upon the button parent element so BEM states use __ prefixing the elements class name.

however the colours for the buttons are stylers so they are not nested (I am not sure about this as I could probably nest this one like below.)

.btn {
padding: 20px;
.btn__value {
color: $valColour;
}
&.btn--gold {
color: $gold;
}
}


I am trying to figure out best practices for this. if anyone has any input Id love to hear it. I am not a big fan of nesting. however since its named btn-- i wouldn't use it any where else.

Answer

I have created quite a simple live example for you to help you understand BEM. Essentially you want to use the ampersand in sass to join class names.

My example has different classnames to help make it clearer, you can see the CSS output and an example of how to use the classes in HTML on the link above.

// ----
// Sass (v3.4.21)
// Compass (v1.0.3)
// ----

$defaultColor: black;
$gold: gold;

// Block
.btn {
  color: $defaultColor;
  padding: 20px;

  // Element
  &__span{
    font-weight: 600;
  }

  // Modifier
  &--no-padding{
    padding: 0;
  }  
  // Modifier
  &--gold{
    color: $gold;
  }
}

Hopefully this helps clear BEM up for you!

Comments