SCSS之基础全解


6个月前 260次点击 来自 前端

原文链接:SCSS之基础全解

1.嵌套选择器

例子1:

body {
  p {
    color: red;
    &:hover {
      color: green;
    }
  }
}

编译后为:

body p {
  color: red;
}
body p:hover {
  color: green;
}

例子2:

body {
  p {
    font: {
      size: 34px;
      family: "Courier";
      weight: bold;
    }
  }
}

编译后为:

body p {
  font-size: 34px;
  font-family: "Courier";
  font-weight: bold;
}

2.变量

变量的类型有六种:

  • 数字,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)
$red: red;
$g: green;

body {
  p {
    color: $red;
    &:hover {
      color: $g;
    }
  }
}

编译后为:

body p {
  color: red;
}
body p:hover {
  color: green;
}

数值计算:

width: 100px + 100px + 100px; //加法
width: 100px - 100px + 100px; //减法
width: 100px * 100 //乘法,注scss的乘法和除法是带单位的
width: (100px/3)  //注意这里需要带括号,如果不带括号会当场分割数子
width: $width / 3 //也可以不带括号,但是里面计算的一定要有声明的变量,因为这个语法css不认识,那么就会被解析成SCSS
width: 100 % 3px //SCSS也支持取模运算

颜色计算

$red:#ff0000;
p{
   color : $red + #888; //#ff8888
}
div{
  color :$red + #111;  //#ff1111
}

字符串插值:

body {
  p {
    $content: "---";
    &:before {
      content: "[#{$content}";
    }

    &:after {
      content: "#{$content}]";
    }
  }
}

3.mixin

@mixin mix {
  border: 1px solid red;
}

body {
  p {
    @include mix;
    color: red;
    &:hover {
      color: green;
    }
  }
}

其中mixin还可以定义为函数,还可以传递参数

@mixin mix($width) {
  border: $width solid red;
}

body {
  p {
    @include mix(2px);
    color: red;
    &:hover {
      color: green;
      @include mix(6px);
    }
  }
}

编译后:

body p {
  border: 2px solid red;
  color: red;
}
body p:hover {
  color: green;
  border: 6px solid red;
}

4.placeholder

%mix {
  border: 1px solid red;
}

body {
  p {
    @extend %mix;
    color: red;
    &:hover {
      color: green;
      @extend %mix;
    }
  }
}

编译后:

body p:hover, body p {
  border: 1px solid red;
}

body p {
  color: red;
}
body p:hover {
  color: green;
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑