less

使用

在引入less.js前先要把你的样式文件引入:

<link rel="stylesheet/less" type="text/css" href="./less/style.less">
<script type="text/javascript" src="./js/less.min.js"></script>

less.js下载

语法

1.变量

@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;

#header { color: @light-blue; }

2.混合

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}
#menu a {
  color: #111;
  .bordered;
}
.post a {
  color: red;
  .bordered;
}

带参数混合

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

@arguments 变量

@arguments包含了所有传递进来的参数. 如果你不想单独处理每一个参数的话就可以像这样写:

.box-shadow (@x: 0, @y: 0, @blur: 1px, @color: #000) {
  box-shadow: @arguments;
  -moz-box-shadow: @arguments;
  -webkit-box-shadow: @arguments;
}
.box-shadow(2px, 5px);

3.模式匹配和导引表达式

如果想让.mixin根据不同的@switch值而表现各异,如下这般设置:

.mixin (dark, @color) {
  color: darken(@color, 10%);
}
.mixin (light, @color) {
  color: lighten(@color, 10%);
}
.mixin (@_, @color) {
  display: block;
}

现在,如果运行:

@switch: light;

.class {
  .mixin(@switch, #888);
}

就会得到下列CSS:

.class {
  color: #a2a2a2;
  display: block;
}

引导

.mixin (@a) when (lightness(@a) >= 50%) {
  background-color: black;
}
.mixin (@a) when (lightness(@a) < 50%) {
  background-color: white;
}
.mixin (@a) {
  color: @a;
}

导引中可用的全部比较运算有: > >= = =< <。此外,关键字true只表示布尔真值,下面两个混合是相同的:

.truth (@a) when (@a) { ... }
.truth (@a) when (@a = true) { ... }

除去关键字true以外的值都被视示布尔假:

.class {
  .truth(40); // Will not match any of the above definitions.
}

导引序列使用逗号‘,’—分割,当且仅当所有条件都符合时,才会被视为匹配成功。

.mixin (@a) when (@a > 10), (@a < -10) { ... }

导引可以无参数,也可以对参数进行比较运算:

@media: mobile;

.mixin (@a) when (@media = mobile) { ... }
.mixin (@a) when (@media = desktop) { ... }

.max (@a, @b) when (@a > @b) { width: @a }
.max (@a, @b) when (@a < @b) { width: @b }

最后,如果想基于值的类型进行匹配,我们就可以使用is*函式:

.mixin (@a, @b: 0) when (isnumber(@b)) { ... }
.mixin (@a, @b: black) when (iscolor(@b)) { ... }

下面就是常见的检测函式:

  • iscolor
  • isnumber
  • isstring
  • iskeyword
  • isurl

如果你想判断一个值是纯数字,还是某个单位量,可以使用下列函式:

  • ispixel
  • ispercentage
  • isem

最后再补充一点,在导引序列中可以使用and关键字实现与条件:

.mixin (@a) when (isnumber(@a)) and (@a > 0) { ... }

使用not关键字实现或条件:

.mixin (@b) when not (@b > 0) { ... }

4.嵌套规则

#header {
  color: black;

  .navigation {
    font-size: 12px;
  }
  .logo {
    width: 300px;
    &:hover { text-decoration: none }
  }
}

5.JavaScript 表达式

JavaScript 表达式也可以在.less 文件中使用. 可以通过反引号的方式使用:

@var: `"hello".toUpperCase() + '!'`;
原文地址:https://www.cnblogs.com/zhoulixue/p/7093894.html