[inheritance] Including another class in SCSS

I have this in my SCSS file:

.class-a{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{

 //Inherite class-a here

 //some properties
}

In class-b, I would like to inherite all properties and nested declarations of class-a. How is this done? I tried using @include class-a, but that just throws an error when compiling.

This question is related to inheritance sass

The answer is


Using @extend is a fine solution, but be aware that the compiled css will break up the class definition. Any classes that extends the same placeholder will be grouped together and the rules that aren't extended in the class will be in a separate definition. If several classes become extended, it can become unruly to look up a selector in the compiled css or the dev tools. Whereas a mixin will duplicate the mixin code and add any additional styles.

You can see the difference between @extend and @mixin in this sassmeister


Combine Mixin with Extend

I just stumbled upon a combination of Mixin and Extend:

reused blocks:

.block1 { box-shadow: 0 5px 10px #000; }

.block2 { box-shadow: 5px 0 10px #000; }

.block3 { box-shadow: 0 0 1px #000; }

dynamic mixin:

@mixin customExtend($class){ @extend .#{$class}; }

use mixin:

like: @include customExtend(block1);

h1 {color: fff; @include customExtend(block2);}

Sass will compile only the mixins content to the extended blocks, which makes it able to combine blocks without generating duplicate code. The Extend logic only puts the classname of the Mixin import location in the block1, ..., ... {box-shadow: 0 5px 10px #000;}


Try this:

  1. Create a placeholder base class (%base-class) with the common properties
  2. Extend your class (.my-base-class) with this placeholder.
  3. Now you can extend %base-class in any of your classes (e.g. .my-class).

    %base-class {
       width: 80%;
       margin-left: 10%;
       margin-right: 10%;
    }
    
    .my-base-class {
        @extend %base-class;
    }
    
    .my-class {
        @extend %base-class;
        margin-bottom: 40px;
    }
    

@extend .myclass;
@extend #{'.my-class'};

Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools