less学习(一):注释、变量、嵌套

本文深入探讨Less预处理器的特性,包括多行与单行注释的使用,变量声明与插值,延迟加载的概念。详细阐述了如何在选择器中嵌套规则,并介绍了父选择器的用法,如创建伪类及生成重复类名。通过实例展示了Less提升CSS编写效率和可维护性的强大功能。
摘要由CSDN通过智能技术生成

一、注释(Comments)

  • 多行注释保留
  • 单行注释不被保留在编译生成的 CSS 中
/* 
 * 一个块注释
 * style comment! 
*/

// 这一行被注释掉了!
div {
  color: red;
}

二、变量(Variables)

基本使用

  • @ 声明变量,作为普通属性值使用
@width: 50px;
@height: 100px;

div {
  width: @width;
  height: @height;
}

变量插值(Variable Interpolation)

  • 变量用于选择器名属性名URL@import语句
  • 需要添加 {}
@my-selector: banner;

.@{my-selector} {
  font-weight: bold;
  line-height: 40px;
  margin: 0 auto;
}
@property: color;

.widget {
  @{property}: #0ee;
  background-@{property}: #999;
}
@images: '../img';

body {
  color: #444;
  background: url('@{images}/white-sand.png');
}
@themes: '../../src/themes';

@import '@{themes}/tidal-wave.less';

延迟加载(Lazy Evaluation)

  • 当一个变量被声明多次,会取最后一次的值,并从当前作用域往外寻找变量。
@var: 0;
.class {
  @var: 1;
  .brass {
    @var: 2;
    three: @var;
    @var: 3;
  }
  one: @var;
}
.class {
  one: 1;
}
.class .brass {
  three: 3;
}

属性名变量(Properties as Variables)

.widget {
  color: #efefef;
  background-color: $color;/*使用$将color属性名当成变量*/
}
.widget {
  color: #efefef;
  background-color: #efefef;
}

三、嵌套(Nesting)

  • Less 提供了使用嵌套(nesting)代替层叠或与层叠结合使用的能力
#header {
  color: black;
  .navigation {
    font-size: 12px;
  }
  .logo {
    width: 300px;
  }
}
``
```css
#header {
  color: black;
}
#header .navigation {
  font-size: 12px;
}
#header .logo {
  width: 300px;
}

四、父选择器 (Parent Selectors)

  • 在嵌套规则中, & 表示父选择器,常用于给现有选择器添加伪类
.header {
  a {
    color: blue;
    &:hover {
      color: green;
    }
  }
}
.header a {
  color: blue;
}
.header a:hover {
  color: green;
}
  • 除此之外,& 还能用于生成重复类名
.button {
  &-ok {
    background-image: url('ok.png');
  }
  &-cancel {
    background-image: url('cancel.png');
  }
  &-custom {
    background-image: url('custom.png');
  }
}
.button-ok {
  background-image: url('ok.png');
}
.button-cancel {
  background-image: url('cancel.png');
}
.button-custom {
  background-image: url('custom.png');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

激洪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值