sass

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?


Solution

  • 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;
    }