一、混合(Mixin)
原css中的样式如:
.header { width:200px; height:100px; } .header .word{ color:red; }
less中的写法可以
.word{ color:red; } .header{ width:200px; height:100px; .word; }
这样写可以减少冗余如果还有别的样式还需要color:red,就可以再次引入.word即可;
二、嵌套规则
less还允许css样式的嵌套,看原来代码写法:
#header { color: black; } #header .navigation { font-size: 12px; } #header .logo { width: 300px; }
现在可以这么写
#header { color: black; .navigation { font-size: 12px; } .logo { width: 300px; } }
三、运算
任何数字、颜色或者变量都可以参与运算。下面是一组案例:
//变量
@base: 5%;
@filler: @base * 2;
@other: @base + @filler;
// 用法
color: #888 / 4;
background-color: @base-color + #111;
height: 100% / 2 + @filler;
四、命名空间&访问器
通过上面我们知道可以这样写样式
#bundle { .button { display: block; border: 1px solid black; background-color: grey; &:hover { background-color: white } } .tab { ... } .citation { ... } }
如果现在我们想把.button的样式写到#header a 里,我们可以这么做
#header a { color: orange; #bundle > .button; }
五、变量范围
像其它编辑语言一样,先找本地如果找不到找父级的范围。
@var: red; #page { @var: white; #header { color: @var; // white } }
在写css中我们经常用到某些通用的样式,但是数值不一样,我们可以这么做
.border-radius(@radius:5px){ -webkit-border-radius:@radius; -moz-border-radius:@radius; border-radius:@radius; } .radius-test{ width:50px; .border-radius(10px); }
这样我们可以把通用的样式抽取出来,不用再写那么多代码
六、函数
Less 内置了多种函数用于转换颜色、处理字符串、算术运算等。这些函数在函数手册中有详细介绍。
函数的用法非常简单。下面这个例子将介绍如何将 0.5 转换为 50%,将颜色饱和度增加 5%,以及颜色亮度降低 25% 并且色相值增加 8 等用法:
@base: #f04615; @ 0.5; .class { width: percentage(@width); // returns `50%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8); } Nam
避免直接编译,让浏览器编译
.width-test{ width:~'calc(300px-10px)'; }
七、父选择符&
a { color: blue; &:hover { color: green; } }
.button {
&-ok {
background-image: url("ok.png");
}
}
.grand {
.parent {
& > & {
color: red;
}
}
}
.header {
.menu {
border-radius: 5px;
.no-borderradius & {
background-image: url('images/button-background.png');
}
}
}
编译后的结果:
a { color: blue; } a:hover { color: green; }
.button-ok {
background-image: url("ok.png");
}
.grand .parent > .grand .parent {
color: red;
}
.header .menu { border-radius: 5px; }
.no-borderradius .header .menu { background-image: url('images/button-background.png'); }
八、条件判断
button when (@my-option = true) { color: white; }
导引中可用的全部比较运算有: > >= = =< <
九、import
你可以在main文件中通过下面的形势引入 .less
文件, .less
后缀可带可不带:
@import "lib.less";
@import "lib";
如果你想导入一个CSS文件而且不想LESS对它进行处理,只需要使用.css
后缀就可以:
@import "lib.css";