Sandy Gifford Sandy Gifford - 7 days ago 6
Sass (Sass) Question

Get ampersand modifier to inherit all properties from parent

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.

Answer

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.