混合mixin函数_Less – Mixin(混合)

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;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值