css|关于预处理器sass、less、stylus🔥🔥

161 阅读1分钟

一、为什么会出现css预处理器

随着前端业务的增加,css代码变得臃肿和难以维护,所以出现了css预编译器

image (18).png

二、预编译器的好处

  • 嵌套代码的能力,通过嵌套来反映不同 css 属性之间的层级关系 ;
  • 支持定义 css 变量;
  • 提供计算函数;
  • 允许对代码片段进行 extend 和 mixin;
  • 支持循环语句的使用;
  • 支持将 CSS 文件模块化,实现复用

三、sass(scss)

sass 使用$进行变量定义

$width:50px;
.test{
    width:$width;
    height: $width+50px;
    background-color:red;
}

sass使用嵌套,不在使用后代选择器> 代码更接近js结构

$width:200px;
.test{
    width:$width;
    height: $width+50px;
    background-color:red;
    .test2{
        width: $width/2;
        height: $width/2;
        background-color: aqua;
    }
}

sass 使用@mixin定义一个可复用的代码块调用,调用一个已经定义的代码块使用@include

@mixin btn-hover {
    width: 50px;
    height: 50px;
    &:hover{
        background-color: cadetblue
    }
}
.btn1{
    @include btn-hover;
}
.btn2{
    @include btn-hover;
}

sass的 &:表示上一层选择器的名字;使用&指向父级选择器

四、less

less使用@定义变量

@width:100px;
.test1{
    width: @width;
    height: @width;
    background-color: aqua;
    .test2{
        width: @width/2;
        height: @width/2;
        background-color: bisque;
    }
}

less使用类来封装重复的代码

/* 定义一个类  @radius定义一个参数,默认值是5px*/
.roundedCorners(@radius: 5px) {
    -moz-border-radius: @radius;
    -webkit-border-radius: @radius;
    border-radius: @radius;
}

.test3 {
    width: 100px;
    height: 100px;
    //   使用这个类 不传参
    // .roundedCorners();
    //传参
    .roundedCorners(50%);
    background-color: red;
}

参数可以有多个,有多个参数时用分号隔开,参数调用时就是通过变量名称,而不是位置。


.mixin(@radius:10px;@color:green;) {
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
  border-radius: @radius;
  color:@color;
}
#header{
    .mixin(@color:green);
  }
  .button{
      .mixin(@color:green);
  }

五、stylus

Stylus声明变量没有任何限定,但变量名和变量值之间的等号=是需要的,完全通过缩进控制,不需要 大括号分号冒号可选。

mainColor = #0982c1
siteWidth = 1024px
$borderStyle = dotted
body
  color mainColor
  border 1px $borderStyle mainColor
  max-width siteWidth

嵌套和less、sass相同

函数的使用

 /* Stylus 定义了一个名叫error的mixin,这个error设置了一个参数“$borderWidth”,
 在没特别定义外,这个参数的值是默认值2px */
error(borderWidth= 2px) {
  border: borderWidth solid #F00;
  color: #F00;
}
.generic-error {
  padding: 20px;
  margin: 4px;
  error(); /* 调用error mixins */
}
.login-error {
  left: 12px;
  position: absolute;
  top: 20px;
  error(5px); /* 调用error mixins,并将参数$borderWidth的值指定为5px */
} 

通过@import引入其它样式文件

@import "reset.css";
@import "file.{type}";
p{
  background:#090909
}

参考👀

blog.csdn.net/erdfty/arti…

blog.csdn.net/qq_41813208…

www.cnblogs.com/wangyingblo…