Less学习(一)----变量(Variables)

变量(Variables)

1. @变量名:值;
@width:400px;
注意:变量实际上是“常量”只能被定义一次

2. 变量不仅可以控制CSS规则里的值,还可以用于其他地方,例如 选择器名,属性名,URLs,@import语句

  • 选择器名
    先定义一个变量
    变量应用于选择器,因为举得例子是类选择器,所以 @ 前面是 ‘.’ ,当是id选择器的时候 @ 前面是 ‘#’
    .@{变量}{
    样式规则
    }
    @my-content: content;
    .@{my-content}{
    样式规则
    }
    Compiles to(编译成)

  • URls
    先定义一个变量
    变量应用于 url 即可
    url("@{变量}具体位置")
    @imgurl: “…/…/pictures”;
    background: url("@{imgurl}/paidaxing.jpg");

  • import
    和URLs一样

  • 属性名
    @color: color;
    @{color}: red;
    background-@{color}: blue;

3. 用一个变量名定义另一个变量
先定义一个变量A
接着定义变量B时,使用 “A” 给变量B赋值
在应用时使用 @@B 即可(相当于 @(@B) ==> @A)
@width: 400px;
@height: “width”;
//表示height为400px
height: @@height;

4. 变量是懒加载,不必在使用之前定义
border-radius: @radius;
@radius: 20px;
这样仍然是能识别出 border-radius: 20px;
注意:当一个变量被定义两次时,改变量首先是在当前作用域查找,它的值取决于当前作用域的最后一个给定的值
@width: 100px;
.container{
@width: 600px;
width: @width;
}
.box{
width: @width;
}
@width:400px;
结果为:
.container的宽度为 600px
.box的宽度为 400px

5. 默认变量,Less已经定义好的变量,如darken()
@self-color: blue;
@self-color2: darken(@self-color,50%);

代码演示
lesscode.vue里的代码如下所示:

<template>
  <div class="lesscode">
    <div class="container">
      <div id="content">
        这是内容区
      </div>
    </div>
    <div class="box"></div>
  </div>
</template>
<script>
export default {
  data(){
    return{

    }
  }
}
</script>
<style lang="less" scoped>
@import "./lesscode.less";
</style>

lesscode.less里的代码如下所示:

@width: 100px;
@border : 1px solid pink;
// 选择器名
@my-content: content;
// URLs
@imgurl: "../../pictures";
// 属性名
@color: color;
// 用一个变量来定义另一个变量
@height: "width";
// 默认变量
@self-color: blue;
@self-color2: darken(@self-color,50%);
.container{
  @width:600px;
  // width为600px,因为当前作用域下的width为 600px
  width: @width;
  // 用一个变量来定义另一个变量
  height: @@height;
  border: @border;
  margin: 0 auto;
  line-height: @width;
  // 属性名
  @{color}: red;

  // 选择器名
  #@{my-content}{
     // width为500px,因为当前作用域下的width为 600px
    width: @width - 100;
    // 用一个变量来定义另一个变量
    height: @@height - 100 ;
    border: @border;
    margin: @width/8 auto;
    // URLs
    // background: url("@{imgurl}/paidaxing.jpg") @width - 100;
    // 属性名
    background-@{color}: @self-color2;
    // 值的懒加载
    border-radius: @radius;
  }
}
.box{
  // width为400px,因为当前作用域下最后一次给 width 的值为400px
  width: @width;
  height: @@height;
  border: @border;
  margin: 60px auto;
}
@radius: 20px;
@width: 400px;

浏览器运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值