Search code examples
sassscss-mixins

Why should I use @extend in SCSS?


In Sass, I could find I can use '@extend' with '@mixin'. But from the code, I got curious what's the advantage of using extend.
If we know which 'classes' exactly what do we have to use, we can just use two classes, not extend and make another class.

In my opinion, if we just use two classes, not making multiple extends, code would be shorter and we can save memory. What can I think of the advantage is it's just more easy to see on 'CSS output', but usually people just check SCSS file, not CSS code output.

Isn't it just better to use two separate classes instead of using multiple extends? What is the main advantage of using '@mixin'?


Solution

  • It helps you write DRY code quickly. @extend can be very useful when used properly.

    It allows a selector to extend the styles of another selector, essentially providing a form of sub-classing. @extend works by combining selectors into a single comma-separated selector.

    I.e. -

    .A {
        font-size: 1rem;
        color:red;
    }
    
    .a{
        @extend .A;
        line-height: normal;
       }
    
    
    Which outputs:
    
    .A,.a {
       font-size: 1rem;
        color:red;
    }
    
    .a{
       line-height: normal;
    }