Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sass @extend and Inheritance

Sass @extend and Inheritance

The @extend directive tells Sass that one selector's styles inherit from another selector.

If one style is almost identical to another with only minor differences, using @extend becomes very useful.

In the following Sass example, we create a basic button style .button-basic, then define two button styles .button-report and .button-submit, both of which inherit from .button-basic. Their main difference is in background and font color, while all other styles are the same.

Sass code:

.button-basic  

{

 

border

:

none

;

 

padding

:

15px

30px

;

 

text-align

:

center

;

 

font-size

:

16px

;

 

cursor

:

pointer

;

}

.button-report  

{

 

@extend

.button-basic

;

 

background-color

:

red

;

}

.button-submit  

{

 

@extend

.button-basic

;

 

background-color

:

green

;

 

color

:

white

;

}

Convert the above code into CSS code as shown below:

CSS code:

.button-basic

,

.button-report

,

.button-submit

{

 

border

:

none

;

 

padding

:

15px

30px

;

 

text-align

:

center

;

 

font-size

:

16px

;

 

cursor

:

pointer

;

}

.button-report

 

{

 

background-color

:

red

;

}

.button-submit

 

{

 

background-color

:

green

;

 

color

:

white

;

}

After using @extend, we no longer need to specify multiple classes like class="button-basic button-report" in the HTML button tag; we only need to set the class="button-report" class.

@extend demonstrates good code reuse.