Search code examples
csssassbem

sass bem element modifier inheriting said elements properties


I know that sass provides us with @extend method that allows me to do this:

%knob {
  width: 10px;
  height: 10px;
}

.house {
  &__door {
    &__knob {
      color: inherit;
      @extend %knob;

      &--red {
        @extend %knob;
        // $1
        color: red;
      }

      &--blue{
        @extend %knob;
        // $1
        color: blue;
      }
    }
  }
}

however i would prefer not to define abstract class %knob at all, would it be possible to reference/include properties defined in __knob (width and height in this case) from within its modifiers --red and --blue?

im including sassmeister snippet here to help out a bit: http://sassmeister.com/gist/58b5b4673a18ecadbba7

example here might not look like an issue but if an element with a long class name has 2 or more different groups of modifiers, and I wont create an abstract class, i sometimes end up with html tags looking like this <p class="some other classes some-house__some-door__some-knob some-house__some-door__some-knob--red">example</p> which I find not very desirable.

what i would like to achieve:

referencing parent element would alow me to reduce this string to <p class="some other classes some-house__some-door__some-knob--red"></p> without necessity of declaring an abstract %knob class

why am I hesitant about using an abstract class here:

declaring an abstract class inside __door element (http://sassmeister.com/gist/bc49e0885342e96a8fbd) gives me this result:

.house__door .house__door__knob, .house__door .house__door__knob--red, .house__door .house__door__knob--blue {
  width: 10px;
  height: 10px;
}

instead of desired

.house__door__knob, .house__door__knob--red, .house__door__knob--blue {
  width: 10px;
  height: 10px;
}

and declaring an abstract class outside of the scope its going to be used in makes the code less readable

or maybe theres a different apporach i could use in order to make my code more readable/maintainable?


Solution

  • while searching for an answer to my question i came to the conclusion that inheriting parent element properties/ using @extend or @include here might not be the best idea as it would work well only if an element had 1 modification at most:

    in other cases if multiple modifications extended same model, and were to be used to the same html element, all of the base properties would be declared multiple times

    also there is no need at all to deeply nest elements (i.e. foo__bar__baz). separating elements makes code easier to maintain.