Extend - Chapter 8

  • 0
There is a subtle but important difference between using mixins and extends.

First, its usage. I remember it like this...
Import the mixin
Extend the class
When mixin only does the copy paste stuff, there by duplicating the same code time and again, extend does the grouping of common styles and wite them as one single class followed by the individual classes with respective unique properties.

.btn {     
  font-family: Arial;
  color: #ffffff;
  font-size: 28px;
  padding: 10px 30px 10px 30px;
  text-decoration: none; 
  color: white; 
}
.one{
   @extend .btn;
   background-color:red;
}
.two{
   @extend .btn;
   background-color:gold;
}
.three{
   @extend .btn;
   background-color:aqua;
}
.four{
   @extend .btn;
   background-color:blueviolet;
}
.five{
   @extend .btn;
   background-color:chocolate;
}

Here we created a normal css class called button and we are "@extend" ing it rather than "@include" ing.



And the css output will be:


Note that the repeating properties has been grouped and written as one single class. Only the background color has been written separately.

What if the same is done via a MIXIN?
Then the same properties will be repeated inside all classes .
@mixin btn {     
  font-family: Arial;
  color: #ffffff;
  font-size: 28px;
  padding: 10px 30px 10px 30px;
  text-decoration: none; 
  color: white; 
}
.one{
   @include btn;
   background-color:red;
}
.two{
   @include btn;
   background-color:gold;
}
.three{
   @include btn;
   background-color:aqua;
}
.four{
   @include btn;
   background-color:blueviolet;
}
.five{
   @include btn;
   background-color:chocolate;
}

The output will be :

See the difference? Getting it?

Multiple extends:
We can extend more than one classes at a time along with the "@extend" command.
.message {
  padding: .5em;
}
.important {
  font-weight: bold;
}
.message-error {
  @extend .message, .important;
}

We can chain extends:
.message {
  padding: .5em;
}
.message-important {
  @extend .message;
  font-weight: bold;
}
.message-error {
  @extend .message-important;
}

Its like B extends A, and C extends B.
So in-effect, C gets everything that A offers and B offers.

Note about Extend and Nested extending:

If we have a nested class ( instead of a plain class ) which we would like to extend, for the record, yes we can do it, but it is not at all recommended as the kind of css specificity that it would be unwinding will make it quite difficult to manage.

We can extend a class, but not a nested selector inside of it.
.header {
  h3 {
    color: red; 
  }
}

.special-header {
  /* Error: can't extend nested selectors */
  @extend .header h3;
}
A good read here.
Avoid sass extends? A different thought here.
Best Practices - Extend

No comments:

Post a Comment