概述

Less 是一门向后兼容的css扩展语言

使用方法

在node.js 环境中使用less

npm install -g less

在浏览器环境中使用less

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.11.1/less.min.js" ></script>

变量

@width: 10px
@height : @width+ 10px
#header {
   
  width: @width,
  height: @height
}

编译为

#header {
   
  width: 10px,
  height: 20px
}

混合

混合是一种将一组属性从一个规则集包含到另一个规则集的方法

.bordered {
   
  border-top: dotted 1px black;
  border-bottom: solid 1px black;
}
#header a {
   
  color: red;
  .bordered()
}

编译为

#header a {
   
  color: red;
  border-top: dotted 1px black;
  border-bottom: solid 1px black;
}

嵌套

Less 提供了使用嵌套(nesting)代替层叠或与层叠结合使用的能力

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

使用less可以这样书写代码

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

还可以使用此方法将伪选择器(pseudo-selectors)与混合(mixins)一同使用

#header a { 
    font-weight: 700;
    font-size: 20px;
    color: red;
    .bordered();
    // less 嵌套结合伪选择器
    &:hover {
   
      color: black
    }
  }