3

I'm using SASS's handy ampersand notation to add BEM-style modifiers to my classes:

.box {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: magenta;

    &--selected {
        background: cyan;
    }
}

I'm exploring the possibility of only having to apply a single class to my elements (ex: <div class="box--selected">...</div> as opposed to <div class="box box--selected">...</div>). I'd like to avoid using @extend, it casts too wide a net. Currently I'm using mixins, which are good, but a little verbose to use for every single class with a modifier.

What I'd really like to do is get &--selected to inherit all the properties from the parent enclosure, and only from the parent enclosure - ie ignore any other class definitions of .box that careless devs may have inserted.

Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65
  • 1
    It's not good idea to allow modifiers to extend all properties. Your output css file will be bigger and bigger more modifies you have. And what if element should have several modifiers? – 3rdthemagical Dec 01 '16 at 09:38
  • @3rdthemagical makes perfect sense. BEM actually recommends that you use both the base and modifier classes anyway - this was more of a thought experiment/feature quandary. – Sandy Gifford Dec 01 '16 at 15:52

1 Answers1

2

I know you've expressed the desire to avoid @extend but this method may allow you to avoid other dev's definitions of .box while still achieving your goal.

You could use placeholders to create your own parent enclosure and extend the placeholder(example of placeholder extension) inheriting only from the placeholder. As a placeholder there is no chance of conflicts with classes from other devs on .box:

%box{
    display: inline-block;
    width: 100px;
    height: 100px;
    background: magenta;
}
.box--selected{
    @extend %box;
    background: cyan;
}

Compared to mixins this method lacks the use of parameters like the following example from the article mentioned above [1]:

@mixin padMasterJ ($param: 10px) {
  padding: $param;
}

Another thing worth noting is that when @extend is used on a parent selection the result will include all nested selectors @extend cannot be used to directly extend a nested selector.

Bonk
  • 447
  • 10
  • 25