Sam Willis
Sam Willis

Reputation: 4211

SASS include parent styles

I am trying to find a way to include the parents styles within nested styles. In the code below, I want to include the width and box-sizing that are set on .random-div in the two nested styles too, so that .random-div--large would have width, box-sizing and padding all set.

.random-div {
    width: 100%;
    box-sizing: border-box;

    &--large {
        padding: 65px 45px;
    }

    &--small {
        padding: 25px 15px;
    }
}

I've tried extending the parent class within the nested ones but that includes all of the other nested styles too. Is there any way to just include the parent styles?

Upvotes: 1

Views: 3332

Answers (3)

Aaron
Aaron

Reputation: 10440

Create a placeholder and use that.

%random-div {
    width: 100%;
    box-sizing: border-box;
}

.random-div {
    &--large {
        @extend %random-div;
        padding: 65px 45px;
    }

    &--small {
        @extend %random-div;
        padding: 25px 15px;
    }
}

This will compile to:

.random-div--large, .random-div--small {
     width: 100%;
     box-sizing: border-box;
}
 .random-div--large {
     padding: 65px 45px;
}
 .random-div--small {
     padding: 25px 15px;
}

Upvotes: 1

Danziger
Danziger

Reputation: 21161

You can use the @extend rule without using a placeholder, just reference the parent class you want to extend:

.random-div {
  width: 100%;
  box-sizing: border-box;

  &--large {
    @extend .random-div;
    padding: 65px 45px;
  }

  &--small {
    @extend .random-div;
    padding: 25px 15px;
  }
}

This will compile to:

.random-div, .random-div--small, .random-div--large {
  width: 100%;
  box-sizing: border-box;
}
.random-div--large {
  padding: 65px 45px;
}
.random-div--small {
  padding: 25px 15px;
}

Note you can't use the parent selector (&) with the @extend rule, so this won't work:

.random-div {
  width: 100%;
  box-sizing: border-box;

  &--large {
    @extend &;
    padding: 65px 45px;
  }

  &--small {
    @extend &;
    padding: 25px 15px;
  }
}

Upvotes: 3

Timotheus0106
Timotheus0106

Reputation: 1586

with your bem methodology your div should have both identifier and modifier and should look like this

<div class="random-div random-div--large"></div>

so it will get all three styles.

Upvotes: 1

Related Questions