@mixin

Here is how the mixin works. The definition and usage:

@mixin awesome {
    width: 100%;
    height: 100%;
}

body {
    @include awesome;
}
p {
    @include awesome;
}

The snippets above produce the following code.

body {
    width: 100%;
    height: 100%;
}
p {
    width: 100%;
    height: 100%;
}

To make the things a little bit more interesting we could make our mixin accepting parameters. Even better we are able to define default values if the mixin is called without arguments.

@mixin awesome($w: 100%, $h: 100%) {
    width: $w;
    height: $h;
}

body {
    @include awesome(960px);
}
p {
    @include awesome;
}

The result will be similar, but the width of the body is different.

body {
    width: 960px;
    height: 100%;
}
p {
    width: 100%;
    height: 100%;
}

If you use mixins the styles in them are duplicated all over your classes

The mixins are very helpful if you need to change or calculate something in the final output. For example, if you need to apply border-radius to several elements. However, in some other cases there is a lot of duplicating code, which could be avoided if you use @extend.

**@extend**

.awesome {
    width: 100%;
    height: 100%;
}

body {
    @extend .awesome;
}
p {
    @extend .awesome;
}

It’s similar, isn’t it. In SASS it looks almost identical, but in the CSS the result is:

.awesome, body, p {
    width: 100%;
    height: 100%;
}

Shorten then the version using a mixin. You can’t pass parameters during the extending, but that’s not the idea actually.

@extend should be used in those places where you want to share properties between the elements.

Advertisements