less学习(五)—关于Mixin

今天进入到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;
}
注意:此处的括号仍然是可选的。












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值