R-b-n
R-b-n

Reputation: 513

Ampersand and mixins in SCSS

Searched but can't find an answer..

I have an element which gets generated (by an external platform) with the following classes: p-button and button.

Now the SCSS is like this:

.p-button {
    &.button {
        margin: 10px;
    }
 }

But I want to refactor using mixin includes (this is a big project so there is no other way of making this code better except using mixins). The mixin takes the given selector and applies a . to it. I can't change the mixin, as it is used by many other teams, so I can't pass the ampersand together with the selector. I tried this:

.p-button {
    & {
        @include button-appearance("button") {
           margin: 10px;
        }
    }
 }

But that doesn't work (puts a space between it). You can't do this:

.p-button {
    &@include button-appearance("button") {
        margin: 10px;
    }
 }

Anyone have a clue?

EDIT: Here is the mixin

@mixin button-appearance(
    $appearance-class, 
    $show, 
    $background-color, 
    $background-image, 
    $background-position) { 
        $sel: $button-selector;
           @if $appearance-class {
                $sel: $sel + '.' + $appearance-class;
         }

#{$sel} {
    @include normalized-background-image($background-image);
    @include show($show);
    background-color: $background-color;
    background-position: $background-position;
    }

    @content;
}

EDIT 2: Here is the $button-selector (I can not edit this in the platform, but maybe overwrite it in my own project?)

$button-class: 'p-button';

$button-selector: '.#{$button-class}';

Upvotes: 4

Views: 1970

Answers (2)

R-b-n
R-b-n

Reputation: 513

Everyone, finally found the solution. I just removed the &.button from the .p-button mixin include and now it works:

@include button-appearance ("button") { *styles* }
@include button-appearance () { *styles* }

Upvotes: 1

muecas
muecas

Reputation: 4335

Edited the answer after the original question was edited adding the used and un modifiable mixin

The original mixin does not append the ‘@content’ passed to the mixin to the generated selector. So if you cannot modify the original mixin, the only way is to add your properties outside the mixin. According to the mixin the selector will match a predefined ‘$button-selector’ variable, so it won’t use your class.

So, if you want to use the same class defined in ‘$button-class’, try the following:

#{$button-selector}.button {
    margin: 10px;
}

Will output:

.p-button.button {
    margin: 10px;
}

Upvotes: 0

Related Questions