CSS预编译器less简单用法

1、变量

定义变量 @变量名:值;

@test_width:100px;

使用变量

.box{
  width:@test_width;
  height:@test_width;
  background-color: red;
}

CSS编译

.box {
  width: 100px;
  height: 100px;
  background-color: red;
}

2、混合(Mixin)

定义样式类

.border{
  border:1px solid black;
}

在box类中通过.border;使用

.box{
    width:@test_width;
    height:@test_width;
    background-color: red;
    .border;
}

CSS编译

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  border: 1px solid black;
}

3、混合嵌套

定义一个html结构

<div >
    <div class="navigation">导航</div>
    <div class="logo"></div>
</div>

使用混合嵌套语法

#header {
  color: black;
  .navigation {
    font-size: 18px;
  }
  .logo {
    width: 100px;
    height: 100px;
    background-color: black;
  }
}

编译结果

#header {
  color: black;
}
#header .navigation {
  font-size: 18px;
}
#header .logo {
  width: 100px;
  height: 100px;
  background-color: black;
}

4、带参数混合

定义一个可传递参数的样式类

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

通过.border-radius(4px);在不同的样式类中调用

.button {
  width:100px;
  height: 40px;
  .border-radius(4px);
}
.button2 {
  width:100px;
  height: 40px;
  .border-radius(20px);
}

通过@radius:5px形式设置默认值

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

调用的时候无需传递默认值.border-radius;

.button3 {
  width:100px;
  height: 40px;
  .border-radius;
}

附:

less教程

http://less.bootcss.com/

使用koala工具编译CSS

http://koala-app.com/index-zh.html