今天进入到Mixin(混合)的学习,经过前面几天的学习已经初步掌握了关于变量和关于Extend的一些语法和规则,如果有朋友觉得我写的实在渣的话,可以移步less官方文档自行学习。
先上一个基本用法的例子
.box1 {
color: red;
}
.box3 {
.box1();
}
编译为:
/* line 1, http://localhost/about-less/styles.less */
.box1 {
color: red;
}
/* line 4, http://localhost/about-less/styles.less */
.box3 {
color: red;
}
注意,在box3的规则集里,.box1后面的括号,官方文档对这个括号有这样一句说明:Notice that when you call the mixin, the parenthesis are optional.(注意,当你使用混合时,括号是可选的。)
Not outputting the mixin(不输出混合)
If you want to create a mixin but you do not want that mixin to be output, you can put parenthesis after it.
(如果你想要创建一个混合,但是又不想输出这个混合,只需要在它后面加一个括号就可以了)
.box1() {
color: red;
}
.box3 {
.box1();
}
输出为:
.box3 {
color: red;
}
Selectors in mixins(混合里的选择器)
Mixins can contain more than just properties, they can contain selectors to.(混合不仅可以包含属性,还可以包含选择器)
.box1() {
&:hover {
border: 1px solid red;
};
}
.box3 {
.box1();
}
输出为:
.box3:hover {
border: 1px solid red;
}
Namespaces(命名空间)
If you want to mixin properties inside a more complicated selector, you can stack up multiple id's or classes.(如果想要在一个复杂的选择器内混合属性,那么可以把id或者类名堆叠起来).box1 {
.box1Child {
color: red;
}
}
.box3 {
.box1 .box1Child;
}
输出为:
/* line 2, http://localhost/about-less/styles.less */
.box1 .box1Child {
color: red;
}
/* line 6, http://localhost/about-less/styles.less */
.box3 {
color: red;
}
如下面这些写法,也会输出同样的结果
.box1 > .box1Child;
.box1 > .box1Child();
.box1 .box1Child;
.box1 .box1Child();
One use of this is known as namespacing. You can put your mixins under a id selector and this makes sure it won't conflict with another library.(可以把混合放在一个(id)选择器后面,这样会确保不会与其他library产生冲突,这种用法被称为命名空间)
#my-library {
.my-mixin() {
color: black;
}
}
// which can be used like this
.class {
#my-library > .my-mixin();
}
The !important keyword(!important关键字)
Use the !important keyword after mixin call to mark all properties inherited by it as !important
.box1(@color1:red,@color2:green) {
color: @color1;
background-color: @color2;
}
.box2 {
.box1()!important;
}
输出为:
.box2 {
color: #ff0000 !important;
background-color: #008000 !important;
}
注意:此处的括号仍然是可选的。