首页 > 开发 > CSS > 正文

动态的样式语言less语法详解之混合属性

2024-07-11 08:30:17
字体:
来源:转载
供稿:网友

前面介绍了less的变量和extend语法,今天在研究下混合属性(Mixin)。混合可以说是less的另一个特征,你可以将通用属性定义在一块,然后使用时直接调用此混合属性。

混合:
  在 LESS 中我们可以定义一些通用的属性集为一个选择器,然后在另一个选择器中去调用这些属性. 例如:


复制代码
代码如下:
.a, #b {
color: red;
}
.mixin-class {
.a();
}
.mixin-id {
#b();
}

编译后


复制代码
代码如下:
.a, #b {
color: red;
}
.mixin-class {
color: red;
}
.mixin-id {
color: red;
}

注意:在调用混合时,可以加括号也可以不加括号。下面这个也是对的:


复制代码
代码如下:
.a, #b {
color: red;
}
.mixin-class {
.a;
}
.mixin-id {
#b;
}

如果你只想定义一个混合,则可以再选择器后面加上括号,如下:


复制代码
代码如下:
.my-mixin {
color: black;
}
.my-other-mixin() {
background: white;
}
.class {
.my-mixin;
.my-other-mixin;
}

编译后,加括号的.my-other-mixin()不会被编译。


复制代码
代码如下:
.my-mixin {
color: black;
}
.class {
color: black;
background: white;
}

任何 CSS class, id 或者 元素 属性集都可以以同样的方式引入.通用选择器中可以嵌套选择器。

命名空间:
  如果你想混合属性在一个更复杂的选择器,可以叠放多个id或类。如下:


复制代码
代码如下:
#outer {
.inner {
color: red;
}
}

如果想使用这个混合属性,你可以这样,下面四个都是等价的


复制代码
代码如下:
.c{
#outer > .inner;
}</p><p>.c{
#outer > .inner();
}</p><p>.c{
#outer.inner;
}</p><p>.c{
#outer.inner();
}

你可以将混合属性定义在一个id的下面,这样就避免了与其他混合冲突。

关键字!important:
  在使用混合属性后面加上!important关键字,则混合中的所有属性都会加上关键字!important。例如:


复制代码
代码如下:
.foo (@bg: #f5f5f5, @color: #900) {
background: @bg;
color: @color;
}
.unimportant {
.foo(1);
}
.important {
.foo(2) !important;
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表