less 使用笔记

作者: CondorHero | 来源:发表于2019-09-25 18:57 被阅读0次

less 官网:http://lesscss.org/

lesscsss

Less (Leaner Style Sheets 的缩写) 的本质:It's CSS, with just a little more. 官网自我介绍,less 是 css ,只是比 css 功能多一点。

node 使用:
npm install -g less
> lessc styles.less styles.css

less 主要涉及的要点:变量,混合,嵌套,函数&运算,扩展。

一、变量
  • less 通过 @ 来定义变量;如:@color:#333;
  • 属性变量,注意必须加一个大括号
body{
    @property:background-color;
    @{property}: red;
}

就这我们就能用 less 的变量结合循环写出一个类似的栅格系统:

.loop(@n) when (@n<=24){
    .col-@{n}{
        float:left;
        width:@n / 24 * 100 + 0%;
    }
    .loop(@n + 1);
}
.loop(1);

编译完成的 css 为:

.col-1 {
  float: left;
  width: 4.16666667%;
}
.col-2 {
  float: left;
  width: 8.33333333%;
}
.col-3 {
  float: left;
  width: 12.5%;
}
.col-4 {
  float: left;
  width: 16.66666667%;
}
.col-5 {
  float: left;
  width: 20.83333333%;
}
.col-6 {
  float: left;
  width: 25%;
}
.col-7 {
  float: left;
  width: 29.16666667%;
}
.col-8 {
  float: left;
  width: 33.33333333%;
}
.col-9 {
  float: left;
  width: 37.5%;
}
.col-10 {
  float: left;
  width: 41.66666667%;
}
.col-11 {
  float: left;
  width: 45.83333333%;
}
.col-12 {
  float: left;
  width: 50%;
}
.col-13 {
  float: left;
  width: 54.16666667%;
}
.col-14 {
  float: left;
  width: 58.33333333%;
}
.col-15 {
  float: left;
  width: 62.5%;
}
.col-16 {
  float: left;
  width: 66.66666667%;
}
.col-17 {
  float: left;
  width: 70.83333333%;
}
.col-18 {
  float: left;
  width: 75%;
}
.col-19 {
  float: left;
  width: 79.16666667%;
}
.col-20 {
  float: left;
  width: 83.33333333%;
}
.col-21 {
  float: left;
  width: 87.5%;
}
.col-22 {
  float: left;
  width: 91.66666667%;
}
.col-23 {
  float: left;
  width: 95.83333333%;
}
.col-24 {
  float: left;
  width: 100%;
}

我们就能在 HTML 直接使用 class 类来调用。

<div class="col-1">1</div>
<div class="col-10">2</div>
<div class="col-10">3</div>
<div class="col-3">4</div>

效果图:


栅格系统
二、混合(Mixin)['mɪksɪŋ] (类似函数)

混合(Mixin)是一种将一组属性从一个规则集包含(或混入)到另一个规则集的方法。

  • 无参数情况
.cur{
    -webkit-transform:rotate(-10deg); /*为Chrome/Safari*/
    -moz-transform:rotate(-10deg); /*为Firefox*/
    -ms-transform:rotate(-10deg); /*为IE*/
    -o-transform:rotate(-10deg); /*为Opera*/
    transform:rotate(-10deg); 
}
main{
    margin:10px;
    border-radius: 5px;
    width: 100px;
    height: 100px;
    background-color: #cfc;
    .cur
}
  • 有参数情况
.cur(@color){
    background-color:@color;
    width: 100px;
    height: 100px;
}
div{
    .cur(#0fc)
}
三、嵌套(Nesting)

Less 提供了使用嵌套(nesting)代替层叠或与层叠结合使用的能力。模仿了 HTML 的组织结构。

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

你还可以使用此方法将伪选择器(pseudo-selectors)与混合(mixins)一同使用。& 运算符表示嵌套规则的父选择器,在修改类或伪类及伪元素时常用。

main{
    width: 100px;
    height: 100px;
    background-color: #fcf;
    &::after {
        content: "我是伪类";
        display: block;
        font-size: 10px;
    }
}
四、注释(Comments)

块注释和行注释都可以使用:

// 会被删除 
/**/ 不会被删除

相关文章

网友评论

    本文标题:less 使用笔记

    本文链接:https://www.haomeiwen.com/subject/zklulctx.html