1. @mixin、@extend优缺点:
①. @minxin相对@extend更可控.
②. 更易减少复杂度:
a. @mixin可以多层嵌套和传入参数
③. 性能:
a. 当被正确的使用@extend会生成更少的CSS是正确的,但是对于性能,mixins的性能更好:
(1). 源文件@extend会更小
(2). gzip压缩@mixins会更小
b. 使用gzip后@mixin比@extend的压缩比更大.
c. 因为gzip是有利于重复代码压缩的.
(1). @extend缺点:
①. 会改变了源命令:在CSS中是相当危险的.
It alters your source order, which is always risky in CSS.
②. 会破坏代码结构合理性:把不相关的选择器串联到一起.
It creates awkward groupings in your code, putting unrelated selectors together.
③. 是非常贪婪的,它会包含一切的代码,而不仅仅是你想要的那一个.
It is very greedy, @extending every instance of a given subject, not just the one you actually wanted...
④. 可能会很快就脱离控制.
It can get really out of control, really fast.
(2). 实验:
两种方式各自生成了1000个独一无二的声明和三个相同的属性语句
①. mixin css文件:
@mixin foo {
color: red;
font-weight: bold;
line-height: 2;
}
// 1000个用Sass生成的独一无二的类
@for $i from 1 through 1000 {
.#{unique-id()}-#{$i} {
@include foo;
content: "ibf#{&}jaslbw"; // 声明了独一无二的内容
}
}
②. extend css文件:
%foo {
color: red;
font-weight: bold;
line-height: 2;
}
// 1000个用Sass生成的独一无二的类
@for $i from 1 through 1000 {
.#{unique-id()}-#{$i} {
@extend %foo;
content: "ibf#{&}jaslbw"; // 声明了独一无二的内容
}
}
③. 对比:
a. mixin.css文件大小 108K 经过gzip后大小 12K
b. extend.css文件大小 72K 经过gzip后大小 18K
https://csswizardry.com/2016/02/mixins-better-for-performance/