sass 笔记

182 阅读2分钟

sass 笔记

@mininx @include @function

mixin 定义混合器 然后使用 include引用之。


  @mixin text{
    color:red;
    font-size:15px;
  }
  
  .title{
    @include text;
    font-weight:600;
  }

混合器 还可以设置变量


  @mixin text($color,$size){
    color:$color;
    font-size:$size;
  }
  
  .title{
    @include text(red,15px);
    font-weight:600;
  }

为便于书写,@mixin 可以用 = 表示,而 @include 可以用 + 表示,所以上面的例子可以写成:

  @mixin: '=' 
  @include : '+'

@extend

extend继承 使用例子


  .text{
    font-size:16px;
    color:red;
    b{
      color:#000;
    }
  }

  .title{
    @extend .text;
    font-weight:bold;
  }

以上例子看着和@include 差不多。

实则:extend 会生成这样的代码


  .text{
    font-size:16px;
    color:red;
  }

  .text b{
    color:#000;
  }

  .title{
    font-size:16px;
    color:red;
    font-weight:bold;
  }

  .title b{
    color:#000;
  }

由这里可知,如果层级比较高则会生成许许多多不可控的css类从而产生bug。

为此 建议在如下情况使用:

1.层级层次很低,可以确保不会出错

  .defu-info{
    font-size:14px;
    color:#999;
  }

  .succsss-info{
    @extend .defu-info;
    color:red;
  }

SassScript

SassScript 的运算等 和 js有些许类似。就不多写了。

变量


  $width:100px;

  body{
    width:$width;
  }

数据类型 (Data Types)

包含以下几种类型


  数字,1, 2, 13, 10px
  字符串,有引号字符串与无引号字符串,"foo", 'bar', baz
  颜色,blue, #04a3f9, rgba(255,0,0,0.5)
  布尔型,true, false
  空值,null
  数组 (list),用空格或逗号作分隔符,1.5em 1em 0 2em, Helvetica, Arial, sans-serif
  maps, 相当于 JavaScript 的 object,(key1: value1, key2: value2)

插值语句

数据类型通过#{}引用

流程控制

@if @else @else if


$type: 'monster';
p {
  @if $type == 'ocean' {
    color: blue;
  } @else if $type == 'matador' {
    color: red;
  } @else if $type == 'monster' {
    color: green;
  } @else {
    color: black;
  }
}

@for @while @each

@for

@for 指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。这个指令包含两种格式:@for $var from <start> through <end>,或者 @for $var from <start> to <end>,区别在于 through 与 to 的含义:当使用 through 时,条件范围包含 <start> 与 <end> 的值,而使用 to 时条件范围只包含 <start> 的值不包含 <end> 的值。另外,var可以是任何变量,比如var 可以是任何变量,比如 i; 和 必须是整数值。

总结一下 就是开闭区间的问题:

through : [start , end ]

to: (start,end)


@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

@each

@each指令的格式是 $var in <list>


$list:'1','2','3';

@each $item in $list {
  .#{$item}-icon {
    background-image: url('/images/#{$item}.png');
  }
}

@while

这个都看得懂:


$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

sass 自定义主题。

参考文章

观后感: 这篇文章的自定义主题其实就是 : 将包裹的元素添加一个根类 ,

然后在根类下 , 生成主题个数的样式 .

当切换的时候切换根类的名字,就可以达到切换主题 .