Mixin是一组共用的CSS属性,类似编程语言中的函数,选择器通过调用Mixin,把Mixin中的属性包含进来。
Less代码:
.round-borders {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#menu {
color: gray;
.round-borders; // 调用mixin: round-borders
}
编译后的css 输出:
.round-borders {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#menu {
color: gray;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
Mixin使用
1. 不输出Mixin本身
Mixin定义带括号,可以让mixin定义本身不输出。
Less代码:
.a() { // 定义带了括号
padding-left: 100px;
}
.myclass {
background : #64d9c0;
.a;
}
编译后的css 输出:
/* 没有输出mixin .a() 的内容 */
.myclass {
background: #64d9c0;
padding-left: 100px;
}
2. Mixin中的选择器
mixin不仅可以包含属性,还可以包含选择器。
Less代码:
.mixin() {
&:hover {
background: #FFC0CB;
}
}
a {
.mixin();
}
编译后的css 输出:
a:hover {
background: #FFC0CB;
}
调用mixin时,括号是可选的。在上面的例子中,调用.mixin()
与调用.mixin
效果相同。
3. 命名空间
命名空间可以将mixin组合到一个公共名称下,这样可避免mixin之间名字冲突。
Less代码:
#outer() {
background:yellow;
.inner {
color: red;
}
}
p {
#outer > .inner;
}
编译后的css 输出:
p {
color: red;
}
4. 受保护的命名空间
当保护应用于命名空间时,只有在保护条件返回true时才使用命名空间定义的mixin。命名空间保护类似于mixin的保护。
Less代码:
@import "https://www.qikegu.com/less/lib.less";
#namespace when (@color = blue) {
.mixin() {
color: red;
}
}
p {
#namespace .mixin();
}
lib.less
@color: blue;
编译后的css 输出:
p {
color: red;
}
5. !important 关键字
important关键字用于覆盖特定的属性。当它被放置在mixin调用之后,它将所有继承的属性都标记为!important。
Less代码:
.mixin() {
color: #900;
background: #F7BE81;
}
.para1 {
.mixin();
}
.para2 {
.mixin() !important;
}
编译后的css 输出:
.para1 {
color: #900;
background: #F7BE81;
}
.para2 {
color: #900 !important;
background: #F7BE81 !important;
}