Less CSS 预处理器

目录

安装

注释

嵌套

变量

操作

命名空间和访问器

扩展 Extend 

混合 Mixins

传递规则集给混合 

函数

Guards

导入 import 

转义字符

合并

父选择器

Less 用法 

Less 插件

程序化使用


安装

        安装 lessc 以供全局使用:

        通过 NPM (节点程序包管理器)在服务器上安装 Less

npm install less -g

        您还可以在包名称后面添加特定版本。 例如: npm install [email protected] -g

        安装到项目开发

npm i less --save-dev

        该命令会安装最新的lessc官方版本到项目文件夹,同时会把它添加到项目 package.json 文件的 devDependencies。 

        Command line usage (命令行使用):

lessc [option option=parameter ...] <source> [destination]

        Examples (例如)

# compile bootstrap.less to bootstrap.css
$ lessc bootstrap.less bootstrap.css

# compile bootstrap.less to bootstrap.css and minify (compress) the result
$ lessc -x bootstrap.less bootstrap.css

注释

        Less CSS 一样,支持两种类型的注释:多行注释和单行注释。只是编译 Less 代码时,单行注释不会显示在 CSS 文件中。

嵌套

        Less 嵌套是具有层级关系的 CSS 样式,CSS 的层级是由 HTML 的结构决定的。Less 嵌套用于具有后代关系和父子关系的选择器中,可以减少代码量,并且使代码结构更清晰。

.class1 {
  .class2 {
    .class3 {
      font-size: 30px;
      color:green;
    }
  }
}

变量

        Less 使用 @ 符号定义变量,语法是:@变量名:变量值。变量可用作插值,变量插值的语法是:"@{变量名}"。

        在样式属性值中使用时,直接用 @variable 即可使用变量;在其他地方,包括选择器名称、属性名称、URL 和 @import 语句使用时,变量必须以插值的形式使用。

@variable: 200px;         //定义变量作为样式属性值使用
@classname: .nav_a;       //变量值不可用中划线,此变量作为插值用于选择器名称

@{classname} {            //作为插值 必须加 “{}”
    width: @variable;     //作为属性值直接使用
}

        变量作用域: 变量将从本地作用域搜索,如果它们不可用,则编译器将从父作用域搜索。变量可以延迟加载,即使变量尚未声明,也可以使用变量。

操作

        Less 支持一些算术运算,例如加号(+),减号( - ),乘法( * )和除法( ),它们可以对任何数字,颜色或变量进行操作。 

@fontSize: 10px;              // 定义一个 Less 变量
.myclass {
 font-size: @fontSize * 2;    // 使用乘法(*)运算符操作变量 @fontSize
}  // 输出:.myclass { font-size: 20px; }

命名空间和访问器

        命名空间用于将 mixins 分组在通用名称下。 使用命名空间可以避免名称冲突,并从外部封装 mixin 组。可以使用 " > " 符号来访问 mixins

#myNamespace {
    .button () { 样式... }    // 在'#myNamespace'命名空间里面声明 mixin ('.button')
}
#header a {
    #myNamespace .button();
    #myNamespace > .button(); // 也可以使用 “>” 符号来访问 mixins ('.button')
}

扩展 Extend 

        Extend 是一个 Less 伪类,它通过使用 ":extend(选择器)" 在一个选择器中扩展其他选择器样式。扩展放置在规则集中或附加到选择器。它类似于包含一个或多个类的伪类,它们之间用逗号分隔。

.style:extend(.container, .img)
{
  background: #BF70A5;
}
.container {
  font-style: italic;
}
.img{
   font-size: 30px;
 }

// 输出
.style {
  background: #BF70A5;
}
.container,
.style {
  font-style: italic;
}
.img,
.style {
  font-size: 30px;
}

         扩展不能检测选择器的重复。

.cont-main{
  font-size: 30px;
}
.cont-main{
  font-size: 30px;
}
.cont:extend(.cont-main, .cont-main) {}

// 输出
.cont-main,
.cont,
.cont {
  font-size: 30px;
}
.cont-main,
.cont,
.cont {
  font-size: 30px;
}

        扩展的关键字 "all"  ,当最后在扩展参数中标识关键字 "all" 时,Less 将扩展所有和拓展参数相关的样式。

.style.nav,
.nav h3 {
  color: orange;
}
.nav {
  &:hover {
    color: green;
  }
}
.container:extend(.nav all) {} //扩展所有和 .nav 相关的样式

// 编译成css
.style.nav,
.nav h3,
.style.container,
.container h3 {
  color: orange;
}
.nav:hover,
.container:hover {
  color: green;
}

混合 Mixins

        Mixin 是一组 CSS 属性,允许您将一个类的属性用于另一个类,在 Less 中,可以使用类或id 选择器以及与 CSS 样式相同的方式声明 Mixin 

.p1{ color:red; }    // Mixins
.p2{ .p1; }
.p3{ .p1(); }

// 输出结果:
.p1 { color: red; }
.p2 { color: red; }
.p3 { color: red; }

        混合可以像函数一样带参数,参数可以使用逗号或分号分隔。当同时使用逗号和分号时,分号用于分隔每一个参数,逗号用于分隔 CSS 列表。

.box-shadow(@x: 0, @y: 0, @height: 3px, @width: 3px) { }
.myclass {
  .box-shadow(2px, 3px, 4px; 5px);// 传入两个参数,第一个参数为 2px,3px,4px,第二个参数为5px
}

        不输出 Mixin:带 " ( ) " 的 Mixin不会输出。

.a(){
  padding-left: 100px;
}
.myclass{
  .a;
}        // 最终CSS文件输出结果:.myclass {  padding-left: 100px; },.a不会输出

        命名参数:Mixins 通过使用它们的名称提供参数值而不是位置。 参数没有放置值的任何顺序,它们可以通过名称引用。

.mixin(@color: black; @fontSize: 10px) {
  color: @color;
  font-size: @fontSize;
}
.class1 {
  .mixin(@fontSize: 20px; @color: #F5A9D0);
}

        @arguments@rest:当调用 Mixin 时, @arguments 包括所有传递的参数。Mixin 通过使用 ... 提供可变数量的参数。通过在变量名称(@rest)后面放置 ... 为变量赋值参数。

.mixin(@x; @rest...) {
    // 使用 ... 提供可变数量的参数
    // @rest 绑定剩余参数
    // @arguments 绑定的是所有参数,包括@x参数
}

        模式匹配:可以通过向 Mixin 传递参数来更改 Mixin 的行为。如果将 @ color-new 的值设置为 dark,则它会以较暗的颜色显示结果,因为 Mixin 定义与 dark 作为第一个参数匹配。

.mixin(dark; @color) {
  color: darken(@color, 15%);
}
.mixin(light; @color) {
  color: lighten(@color, 15%);
}
@color-new: dark;
.line {
  .mixin(@color-new; #FF0000);
}

        Mixin  中的变量可以在调用者的作用域中使用,并且是可见的。

        混合和函数的工作方式非常相似,Mixin 也可以嵌套,可以接受参数和返回值。

.padding(@x, @y) {
  @padding: ((@x + @y) / 2);    // @padding 会当做返回值
}
.myclass{
  .padding(80px, 120px);        // call to the mixin
  padding-left: @padding;
}

.outerMixin(@value) {           // 混合nestedMixin 会当做返回值
  .nestedMixin() {
    font-size: @value;
  }
}
.myclass {
  .outerMixin(30);
  .nestedMixin();
}

传递规则集给混合 

        分离(detached)规则集合是一组 CSS 属性,嵌套的规则集合,媒体声明或是存储在一个变量中的任何其他东西。你可以将其包含到一个规则集合或其他结构中,它的所有属性将被复制在那里。你也可以使用它作为一个 mixin 参数,并传递它周围的其他任何变量。

// 声明 detached 规则集合
@detached-ruleset: { background: red; };

// 使用 detached 规则集合
.top { @detached-ruleset(); }    // 编译结果:.top { background: red; }

        调用时分离(detached)规则集合后面的圆括号是必须的, @detached-ruleset ; 这样调用是无效的。

        当你希望定义一个 mixin 将一个媒体查询中的一个代码块或者一个浏览器不支持的类名抽象出来时很有用。规则集合可以传递规则集给 mixin,所以该 mixin 会包装这些内容。比如:

.desktop-and-old-ie(@rules) {
  @media screen and (min-width: 1200) { @rules(); }
  html.lt-ie9 &                       { @rules(); }
}

header {
  background-color: blue;

  .desktop-and-old-ie({
    background-color: red;
  });
}

         分离规则集合可以在它被定义和被调用的地方使用所有变量和混入。换句话说, 定义和调用的作用域对它都是有效的。如果这两个作用域包含相同的变量或混入,声明的作用域中的值优先。

@detached-ruleset: {
  @msg:declareMsg;                     // 声明中定义的变量 @msg
  msg:@msg;
  caller-variable: @callerVariable;    // 这里变量是 undefined
  .callerMixin();                      // 这里混合是 undefined 
};

selector {
  @detached-ruleset();                 // 使用分离规则集合
  
  @msg:callerMsg;                      // 调用中定义的变量 @msg (将被忽略)

  // 需要在分离规则集合内定义变量和混合
  @callerVariable: value;
  .callerMixin() {
    color: red;
  }
}

// 编译结果:
selector {
  msg: declareMsg;
  caller-variable: value;
  color: red;
}

        定义分离规则集合体的声明的作用域是独立的。从一个变量复制分离规则集合到另一个不能修改其作用域。规则集合不会获得新的作用域,只是在那里被引用。

@detached-1: { scope-detached: @one @two; };
.one {
  @one: visible;    // 规则集合不能使用 visible
  .two {
    @detached-2: @detached-1; // 拷贝/重命名 规则集合 
    @two: msg;
  }
}

.usePlace {
  .one > .two(); 
  @detached-2();
}

// 编译结果:
NameError: variable @one is undefined

        最后,分离规则集合可以通过被解锁(导入)获得到它作用域。

#space {
  .importer1() {
    @detached: { scope-detached: @variable; }; // 定义分离规则集合
  }
}

.importer2() {
  @variable: value;     // 解锁分离规则集合能使用这个变量
  #space > .importer1();// 解锁/导入分离规则集合
}

.usePlace {
  .importer2();         // 第二次解锁/导入分离规则集合
   @detached();
}

// 编译结果:
.usePlace {
  scope-detached: value;
}

函数

        Less 映射具有值操作的 JavaScript 代码,并使用预定义的函数来操纵样式表中的 HTML 元素。Less 提供了许多用于转换颜色,处理字符串和进行算术运算的函数。。

@color: #FF8000;
@width:1.0;
.mycolor{
    color: @color;
    width: percentage(@width);    // 函数 percentage() 将浮点数转换为百分比字符串
}
// 编译结果:
.mycolor {
    color: #FF8000;
    width: 100%;
}

        更多类型的函数具体看下面链接:Less 函数参考http://shouce.jb51.net/less/functions/index.htm

Guards

        Guards 可以用于在表达式上匹配简单的值或参数数量,类似于 if / else 语句,但是 Less 使用 Guards 而不是 if / else 语句,并执行计算以指定匹配。使用 when 关键字引进了一个 guard序列。此外,default 函数可以用于让一个 Mixin 匹配依赖于其他 Mixin 匹配,然后你可以使用它来创建类似于 else  或者 default 语句(分别属于 if 和 else 结构)的“条件式 Mixins”:

.mixin (@a) when (@a > 0) { ...  }
.mixin (@a) when (default()) { ... } // matches only if first mixin does not, i.e. when @a <= 0

        Less 包含五个保护比较运算符:<><=>= =。 您可以使用比较运算符(=)来比较数字,字符串,标识符等,而剩余的运算符只能与数字一起使用。

.mixin (@a) when (@a >= 20px){
	color:red;
}

.myclass { .mixin(20px) } // 输出:.myclass { color: red; }

         Less 逻辑运算符使用关键字 and,并使用 not 关键字取消条件。

.mixin (@a) when not (@a< 20px) and not (@a > 50px){
	font-size: @a;
} 
.class1 { .mixin(30px) }// 输出:.class1 { font-size: 30px; }

        Less 可以使用类型检查内置函数来确定匹配值类型 。

        Guards 可以使用于命名空间,mixinscss 选择器 

@usedScope: global;
@usedMixin: use;
#namespace when (@usedScope = global) {        // 命名空间使用 Guards 
	.mixin (@color) when(@usedMixin = use) {   // mixin 使用 Guards 
      .cont when (@color = red) {              // CSS 样式使用 Guards 
        background-color: red;
        color: black;
      }
      .style when not (@color = red) {         // CSS 样式使用 Guards 
        background-color: blue;
        color: white;
      }
	}
}
p{
     #namespace .mixin(blue);
}

导入 import 

        Less 中,可以通过 @import 指令来导入外部文件。

        文件拓展名:如果您使用 .css 扩展名,那么它将被视为 CSS ,如果不使用拓展名或者使用其他任何拓展名,那么它将被视为 Less 并将被导入。

@import "style";      // imports the style.less
@import "style.less"; // imports the style.less
@import "style.php";  // imports the style.php as a less file
@import "style.css";  // it will kept the statement as it is

        导入选项:可用的关键字如下:

reference 它使用一个Less文件作为参考,不会输出它。
inline 它使您能够将CSS复制到输出而不进行处理。
less 它会将导入的文件视为常规Less文件,尽管可能是其他文件扩展名。
css 它会将导入的文件视为常规CSS文件,尽管可能是其他文件扩展名。
once 它将只导入一次文件。
multiple 它会多次导入文件。
optional 即使找不到要导入的文件,它仍会继续编译。

        允许在 @import 语句中使用多个关键字,但必须使用逗号分隔关键字。比如:

@import (less, optional) "custom.css";

转义字符

        有时候,当需要引入无效的 CSS 语法或 Less 不能识别的字符,就需要使用转义字符。此时,就可以在字符串前面加一个 ~,并将需要转义的字符串放在 " " 中。格式为:~"anything"

.weird-element {
  content: ~"some horrible but needed css hack";
} // 输出:.weird-element { content: some horrible but needed css hack; }

合并

        它是 Less 的一个特性,用于添加属性值。目前只支持两种类型的合并,使用“+”标识添加属性值,并以逗号分隔添加的值,使用“+_”标识添加属性值,并以空格分隔添加的值。

// 使用 “+” 标识
.class {
  box-shadow+: 5px 5px 5px grey;
  box-shadow+: 0 0 5px #f78181;
}    //结果为:.class { box-shadow: 5px 5px 5px grey, 0 0 5px #f78181; }

// 使用 “+_” 标识
.class {
  transform+_: scale(1);
  transform+_: rotate(2deg);
}    //结果为:.class { transform: scale(1) rotate(2deg); }

父选择器

        可以使用 & (和号)运算符来引用父选择器,并且在修改类或伪类选择器的应用中非常普遍。

        & 将代表最近的选择器以及所有父选择器,通过使用 & 运算符,可以重复引用父选择器,而不使用其名称。

.select {
  && {
    color: #81BEF7;
  }

  &, &_class1 {
    color: #A4A4A4;
  }
}

// 输出
.select.select {
  color: #81BEF7;
}
.select,
.select_class1 {
  color: #A4A4A4;
}

        将 后置,可以改变选择器的顺序,将当前的选择器提到父级。

.side{
  div&{
    color:cyan;
  }
}
// 输出
div.side {
  color: cyan;
}

        组合爆炸:当多个同级选择器用“”隔开时,其子级使用连续多个 时,例如 &+& 或 &-&等,会生成所有可能的组合。

div,p{
  &+&{
    color:red;
  }
}
// 输出为
div + div,
div + p,
p + div,
p + p {
  color: red;
}

Less 用法 

Less 插件

        在 command line 中使用插件,首先需要安装插件,以 less-plugin-clean-css 插件为例:

npm install -g less-plugin-clean-css

        然后通过 Lessc 命令使用插件,格式为:

lessc --plugin=PLUGIN=OPTIONS

# 以 less-plugin-clean-css 插件为例
lessc --plugin=less-plugin-clean-css="advanced"

        如果插件名字以“less-plugin”开头,可以使用简便写法,还以 less-plugin-clean-css 插件为例:

lessc --clean-css="advanced"    

        在代码中使用插件,以 less-plugin-clean-css 为例:

var LessPluginCleanCSS = require('less-plugin-clean-css'),
cleanCSSPlugin = new LessPluginCleanCSS({advanced: true});
less.render(lessString, { plugins: [cleanCSSPlugin] })
   .then(function(output) {
    },
    function(error) {
    }
);

        在浏览器使用插件,在 less.js 脚本之前,应该先引入插件对应的 JavaScript 文件。

<script src="plugin.js"></script>
<script>
less = { 
    plugins: [plugin]
};
</script>  
<script src="less.min.js"></script>

程序化使用

        进入 less 的切入点是 less.render 函数,使用格式如下:

less.render(lessInput, options)
    .then(function(output) {
        // output.css = string of css
        // output.map = string of sourcemap
        // output.imports = array of string filenames of the imports referenced
    },
    function(error) {
    });

// or...

less.render(lessInput, options, function(error, output) {})

        您可以通过添加侦听器来访问日志,如下面的格式所示:

less.logger.addListener({
    debug: function(msg) {
    },
    info: function(msg) {
    },
    warn: function(msg) {
    },
    error: function(msg) {
    }
});

猜你喜欢

转载自blog.csdn.net/weixin_42754922/article/details/123604463