less常用语法介绍

Less是一门CSS预处理语言,它扩展了CSS语言,增加了变量、Mixin、函数等特性,使CSS更易维护和扩展。本文就来为大家介绍一下less中常用的语法,希望对大家有一定的帮助。

变量@

变量插值

@mySelector: banner;
.@{mySelector} {
  font-weight: bold;
}

延迟加载

变量是延迟加载的,在使用前不一定要先申明

.brass {
   @var: 2;
   three: @var;       //这是的值是3,同级别中最后一个,顺序无所谓
   @var: 3;
}

合并属性

使用“+”,“+_”,合并同一个css样式的属性,前者用逗号隔开,后者用空格隔开。

.mixin() {
  transform+_: scale(2);
}
.myclass {
  .mixin();
  transform+_: rotate(15deg);
}

=>
.myclass {
  transform: scale(2) rotate(15deg);
}

扩展 extend

nav ul {
  &:extend(.inline);
  background: blue;
}
.inline {
  color: red;
}

=>
nav ul {
  background: blue;
}
.inline,
nav ul {
  color: red;
}

混合 mixins

//混合“类”选择器或者“id”选择器
.a {
  color: red;
}
.mixin-class {
  .a();
}

//不输出混合集
.my-mixin {
  color: black;
}
.my-other-mixin() {                 
  background: white;
  &:hover {
    border: 1px solid red;
  }
}
.class {
  .my-mixin;
  .my-other-mixin;
}
=>
.my-mixin {
  color: black;
}
.class {
  color: black;
  background: white;
}
.class:hover {
  border: 1px solid red;
}

//!important
.foo (@bg: #f5f5f5, @color: #900) {
  background: @bg;
  color: @color;
}
.important {
  .foo() !important;
}
=>
.important {
  background: #f5f5f5 !important;
  color: #900 !important;
}

带参数混合

//带参数的混合 
.border_width1(@b_width){ 
    border: solid blue @b_width; 
} 
.test_mix1{ 
    .border_width1(5px); 
} 
=>
.test_mix1 { 
    border: solid #0000ff 5px;
} 

//参数有默认值的混合 
.border_radius(@radius:5px){ 
    border-radius: @radius; 
} 
.test_radius{ 
    .border_radius(); 
    height: 20px;  
}
=>
.test_radius { 
    border-radius: 5px; 
    height: 20px;
}

//参数通过它的名称来引用
.mixin(@color: black; @margin: 10px; @padding: 20px) {
  color: @color;
  margin: @margin;
  padding: @padding;
}
.class1 {
  .mixin(@margin: 20px; @color: #33acfe);
}
=>
.class1 {
  color: #33acfe;
  margin: 20px;
  padding: 20px;
}

模式匹配

.mixin(dark; @color) {
  color: darken(@color, 10%);
}
.mixin(light; @color) {
  color: lighten(@color, 10%);
}
.mixin(@_; @color) {
  display: block;
}

@switch: light;
.class {
  .mixin(@switch; #888);
}

有的时候,需要一次性将所有的参数全部传进去,此时使用@arguments可以更加方便。

//@arguments代表传进所有的参数 
.border_arg(@c:red,@w:3px,@x:solid){ 
    border:@arguments; 
} 
.test_arg{ 
    .border_arg(40px);  
}

注释

// 不会被编译到css文件中

/**/ 会编译到css文件中

避免编译

有些情况下,我们不需要less中的某些内容被自动编译,而是保留下来原样放到CSS中,此时可以使用~''

.test_avoid{
    width: ~'(300px-100px)';
}
=>
.test_avoid {
  width: (300px-100px);
}
.test{
    height: calc(~'100% - 100px');
}
=>
.test {
  height: calc(100% - 100px);
}

高级用法

循环

.loop(@counter) when (@counter > 0) {
  .loop((@counter - 1));    
  width: (10px * @counter); 
}

div {
  .loop(3);       // 调用循环
}
=>
div {
  width: 10px;
  width: 20px;
  width: 30px;
}

推荐:css参考手册

以上就是less常用语法介绍的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS 教程