Mark Sandman
Mark Sandman

Reputation: 3333

Pass argument to Sass BEM mixin to @extend parent

I am creating an app that will have different css backgrounds depending on the content or the location the user is within the app. I need to apply the following modifiers to various classes within my app. I have written a mixin for this that looks like so:

@mixin animalBackground($arg:null) {

    @if ($arg) {
        @extend $arg;
    }

    &--cat {
        background: $grey url('/img/cat.png');
    }

    &--dog {
        background: $blue url('/img/dog.png');
    }

    &--mouse {
        background: $light-green url('/img/mouse.png');
    }
}

Now I have various places where I want to add this mixin so i can have the 3 different modifier classes, this is how I would add it to my existing sass code:

.animal-section {

     &__target1 {
        overflow-y: scroll;
        height: 100%;
        @include animalBackground();
    }

    &__target2 {
            padding-top: $full-header-size;
            height: 100vh;
            @include animalBackground('.animal-section__target2');
    }
}

Now the problem I have is that within my generated code is getting an error that failed to @extend "$arg". The selector "$arg" was not found. When I remove the if condition the parent class isn't extended / inherited. How do I accomplish what I need to get done?

Thanks in advance.

Upvotes: 1

Views: 459

Answers (1)

RWAM
RWAM

Reputation: 7018

I think you must use the value of the variable. So you should try this:

@if ($arg) {
    @extend #{$arg};
}

Upvotes: 1

Related Questions