less语法

1 变量

@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;
#header { color: @light-blue; }

2 混合

#menu a { color: #111; .bordered; }

3 嵌套

#header {
color: black;
.navigation { font-size: 12px; }
.logo { width: 300px; }
}

.clearfix {
display: block;
zoom: 1;
&:after {
content: ” “;
display: block;
font-size: 0;
height: 0;
clear: both;
visibility: hidden;
}
}

.button {
&-ok { background-image: url(“ok.png”); }
&-cancel { background-image: url(“cancel.png”); }
&-custom { background-image: url(“custom.png”); }
}

4  运算

任何数字、颜色或者变量都可以参与运算。下面是一组案例:

@base: 5%;
@filler: @base * 2;
@other: @base + @filler;
color: #888 / 4;
background-color: @base-color + #111;
height: 100% / 2 + @filler;

5  函数

Less 内置了多种函数用于转换颜色、处理字符串、算术运算等。这些函数在函数手册中有详细介绍。

函数的用法非常简单。下面这个例子将介绍如何将 0.5 转换为 50%,将颜色饱和度增加 5%,以及颜色亮度降低 25% 并且色相值增加 8 等用法:

@base: #f04615;
@width: 0.5;
.class {
width: percentage(@width); // returns `50%`
color: saturate(@base, 5%);
background-color: spin(lighten(@base, 25%), 8);}

6 导入

@import “library”; // library.less @import “typo.css”;

7 selector

// Variables
@mySelector: banner;
// Usage
.@{mySelector} { font-weight: bold; line-height: 40px; margin: 0 auto; }

1.8 URLs

// Variables
@images: “../img”;
// 用法
body {  color: #444;  background: url(“@{images}/white-sand.png”);}

1.9 extend

@media screen {
.selector/* ruleset inside nested media – top level extend works */
color: blue;}
@media (min-width: 1023px) {
.selector/* ruleset inside nested media – top level extend works */
color: blue;}
}
}
.topLevel:extend(.selector) {} /* top level extend matches everything */

compiles into:

@media screen {
.selector,
.topLevel { /* ruleset inside media was extended */
color: blue;
}
}

@media screen and (min-width: 1023px) {
.selector,
.topLevel { /* ruleset inside nested media was extended */
color: blue;
}
}

1.10  带参数的Mixin

.border-radius(@radius) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}

And here’s how we can mix it into various rulesets:

#header {
.border-radius(4px);
}

.button {
.border-radius(6px);
}