css预处理器

69 阅读2分钟

less语法

  1. 完全兼容css
  2. 变量 @变量名:变量值
@themeColor:#ff6d00;
@mainFontSize:15px;
p {
    color:@themeColor;
    font-size:@mainFontSize;
}
  1. 嵌套

在css中,要找到一个元素需要嵌套很多层选择器,Less提供了选择器的嵌套。

<div class="container">
    <div class="box">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>
  </div>
.container{
  height: 200px;
  width: 200px;
  background: @mainColor;
  .box{
    width: 100px;
    height: 100px;
    background: cadetblue;
    // & 表示当前选择器的父级
    &:hover{
      background: palegreen;
    }
    .item{
      &:nth-child(1){
        color: red;
      }
    }
  }
}
  1. 运算:在Less中,算术运算符 +、-、*、/ 可以对任何数字、颜色或变量进行运算。 算术运算符在加、减或比较之前会进行单位换算,计算双方只要有一方携带单位,结果就带有单位,左右两侧都有单位,计算的结果以最左侧操作数的单位类型为准;
.box{
    width: 100 - 10vw;// 90vw
    height: 100px * 2;
    background: #ff0000 + #00ff00;
  }
  1. 混合 mixin 在原来的CSS编写过程中,多个选择器中可能会有大量相同的代码 我们希望可以将这些代码进行抽取到一个独立的地方,任何选择器都可以进行复用; 在less中提供了混入(Mixins)来帮助我们完成这样的操作;
.ellipsis{
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.box_border(@borderWidth:5px,@borderColor:purple){
    border:@borderWidth solid @borderColor;
}
.item{
  .ellipsis();  // 也可以不用()
  .box_border(10px , yellow);
}
  1. 映射
.box_size{
    width:100px;
    height:100px;
}
.item{
    width:.box_size()[width]
}

.pxToRem(@px){
    result:(@px / @htmlFontSize) * 1rem
}
.box{
    width:.pxToRem(100px)[result]
}
  1. 继承: 和mixins作用类似,用于复用代码; 和mixins相比,继承代码最终会转化成并集选择器;
.box_size{
    width:100px;
    height:100px;
}
.item{
    &:extend(.box_border)
}
  1. 内置函数:less.bootcss.com/functions/
color():对颜色进行转换
convert():单位转换
ceil()
floor()
.......
  1. 作用域

在查找一个变量时,首先在本地查找变量和混合(mixins); 如果找不到,则从“父”级作用域查找;

  1. 注释

//、/**/

  1. 导入:导入的方式和CSS的用法是一致的,@import

scss语法:sass-lang.com/guide

  1. 变量:$变量名:变量值
  2. 混合 mixin
// 定义@mixin
// 使用@include
@mixin theme($theme: DarkGray) {
  background: $theme;
  box-shadow: 0 0 1px rgba($theme, .25);
  color: #fff;
}
.info {
  @include theme;
}
  1. 继承
%message-shared {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}
.message {
  @extend %message-shared;
}