LESS differences between mixin and extend [closed]

淺唱寂寞╮ 提交于 2019-12-06 05:58:48

Before the differences, it is important to delve into what mixins and extend are

Mixins

Mixins are common rule-sets you define and can use them in any other rule-sets, eg.

.highlighted-text {
  color: #CCCCCC;
}
.normal-text:hover {
  .highlighted-text;
  font-size: 14px;
}
.another-text {
  .highlighed-text;
}

This will compile to

.highlight-text {
  color: #CCCCCC;
}
.normal-text:hover {
  color: #CCCCCC;
  font-size: 14px;
}
.another-text {
  color: #CCCCCC;
}

What we just did was mixing in of the rule-set we defined as .highlighted-text into any other rule-sets we deemed fit.

Mixins end up being very strong in that you can define one common rule-set, say .bordered, and mix it into all elements you want bordered. These help you in keeping your code DRY, and to change the styling of bordered elements across your page(s), you just need to change it at one place.

Another defining feature of mixins is that you can use multiple mixins in the same rule-set.

.bordered {
  border: 1px solid black;
}
.rounded {
  border-radius: 5px;
}
.bordered-and-rounded {
  .bordered;
  .rounded;
}

This feature basically allows your code to be as flexible as you will make it. Define a bunch of mixins and combine them to get the UI/UX you want.

Finally, mixins can be defined as functions with parameters as well, so you can have something like

.translucent(@opacity) {
  opacity: @opacity;
}
.medium-translucence {
  .translucent(0.5);
}
.high-translucence {
  .translucent(0.25);
}

Extend

Extend works in a very similar way as OOP works. You define a parent rule-set and you establish a chain of inheritance to inherit the same style. Consider this example

.black-text {
  color: #000000;
}
.title {
  &:extend(.black-text);
  font-size: 24px;
}

You have just 'extended' the behaviour of .black-text by inheriting the rule-set into title and adding a rule of your own.

The result CSS will be:

.title {
  font-size: 24px;
}
.black-text,
.title {
  color: #000000;
}

TL;DR - Differences between Extend and Mixin

Mixins allow you to write code in a more generic way, wherein you can include standard coding constructs, such as branching and looping to generate CSS more flexibly. This is possible since mixins allow for parameters and behave as functions when they do.

Extend allows you to inherit a set of static properties from one rule-set to another and you can augment the inherited rule-set with rules of your own.

Note - This answer is by no means the most comprehensive one in terms of usage, since the concept of mixins and extend is fairly broad. The best place to learn about the usage is the LESS docs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!