Search code examples
includesassextend

Something between @include and @extend with sass


Is it possible to include a css rule in sass without duplicate the code? With extend we are extending the code, but i dont want that eiter. I want include it, without duplicating code.

For example

SCSS:

.heading {
    font-size: 16px;
    font-family: my-cool-font;
}

.box {
    background: red;
    h1 {
        @extend .heading;
        color: white;
    }
}

.my-other-box {
    .heading {
        color: black;
    }
}

HTML

<div class="box">
   <h1>My heading</h1>
</div>
<div class="my-other-box">
   <h1 class="heading">My heading</h1>
</div>

CSS

.heading, .box h1 {
    font-size: 16px;
    font-family: my-cool-font;
}
.box {
    background: red;
 }
.box h1 {
    color: white;
}

.my-other-box .heading,
.my-other-box .box h1,
.box .my-other-box h1 {
    color: black;
}

So the two last rules there are because its extending (I understand the benifits of it). But if i want to both use classes, and extends i dont want it to extend, just include it. But i dont want it to duplicate the code.

I want:

CSS

.heading, .box h1 {
    font-size: 16px;
    font-family: my-cool-font;
}
.box {
    background: red;
 }
.box h1 {
    color: white;
}

.my-other-box .heading {
    color: black;
}

Solution

  • If you use an extend class (or use a class name that differs from one you're repeating elsewhere), you can get the output you're looking for:

    %heading, .heading {
        font-size: 16px;
        font-family: my-cool-font;
    }
    
    .box {
        background: red;
        h1 {
            @extend %heading;
            color: white;
        }
    }
    
    .my-other-box {
        .heading {
            color: black;
        }
    }
    

    Output:

    .box h1, .heading {
      font-size: 16px;
      font-family: my-cool-font;
    }
    
    .box {
      background: red;
    }
    
    .box h1 {
      color: white;
    }
    
    .my-other-box .heading {
      color: black;
    }