In Sass, what's the difference between Mixins and Extend?

I just finished with the sass guide . The manual explains mixins:

.. Mixin allows you to create CSS ad groups that you want to reuse on your site. You can even pass values ​​to make mixin more flexible.

and Extend:

.. This is one of the most useful features of Sass. Using @extend allows you to share a set of CSS properties from one selector to another.

It looks like Extend can be implemented in mixin (it seems mixin is an extension of extend :-)).

// @extend
.message {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  @extend .message;
  border-color: green;
}

.error {
  @extend .message;
  border-color: red;
}

.warning {
  @extend .message;
  border-color: yellow;
}

// @mixin
@mixin message($color) {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: $color;
}

.success { @include message(green); }

.error { @include message(red); }

.warning { @include message(yellow); }
Run codeHide result

and even more because mixing has parameters. but, on the other hand, the processed css is not quite the same. but it will be the same style effect for the DOM.

/* extend processed */
.message, .success, .error, .warning {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333; }

.success {
  border-color: green; }

.error {
  border-color: red; }

.warning {
  border-color: yellow; }

/* mixin processed */

.success {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: green; }

.error {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: red; }

.warning {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: yellow; }
Run codeHide result

, ? ?

+4
2

@mixin

, mixin. :

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

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

.

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

, mixin . , mixin .

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

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

, .

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

mixins,

, - . , . , , @extend.

**@extend**

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

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

, . SASS , CSS :

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

, mixin. , .

@extend , .

+3

, Mixin , , extend cop-paste code

+1

Source: https://habr.com/ru/post/1679048/


All Articles