sass的使用

194 阅读1分钟

什么是sass?

sass作为一种css预处理语言,使用起来是真香,简化了css,简化了css,一系列的特性反正是非常好用啊,改起来也比较好改,维护和可读性都比较高。

sass与css、less的区别

sass与css

sass在css的基础上增加了好多的功能,包括mixin,变量,继承,一系列的指令等。

sass与less

  • sass与less的编译环境不同,sass是在Ruby的基础上进行编译的,而less是在less.js的基础上,编译成css放到浏览器上。
  • sass的变量用$,less的变量用@。
  • sass支持条件语句,if{},else{},for{}等。

变量

如果是频繁使用的可以用变量,减少复写。 例如:

$color: #ccc;
.box {
   color: $color;
}
等同于
.box {
    color: #ccc;
}

mixin

混入:是可复用的代码块。可通过@include进行复用。

@mixin icon {
    width: 20px;
    height: 20px;
}
.box {
    @include icon;
    vertical-align: middle;
}
等同于:
.box {
    width: 20px;
    height: 20px;
    vertical-align: middle;
}

继承

sass允许一个选择器继承另一个选择器。

.father {
    margin-left: 5px;
}
.son {
    @extend .father;
    top: 5px;
    
}
等同于
.father,.son {
    margin-left: 5px;
}
.son {
    top: 5px;
}

嵌套

嵌套有选择器嵌套和&嵌套。

  • 选择器嵌套
nav {
    ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }
    li {
        display: inline-block;
    }
}
等同于
nav ul {
    margin: 0;
    padding: 0;
    list-style: none;
}
nav li {
    display: inline-block;
}

  • &用法
.box {
    opacity: 0;
    width: 20px;
    height: 20px;
  &:hover {
      opacity: 1;
  }
}
等同于
.box {
    opacity: 0;
    width: 20px;
    height: 20px;
    
}
.box:hover {
     opacity: 1;
}

导入

  • @import命令,用来插入外部文件。
  • 如果插入的是.css文件,则等同于css的import命令。
@import "common/index.scss";

@import "foo.css";

指令

  • 条件语句 如果条件成立不为false或者null时,编译成功
p {
  @if 1 + 1 == 2 { border: 1px solid; }
  @if 5 < 3 { border: 2px dotted; }
  @if null  { border: 3px double; }
}
等同于
p {
    border: 1px solid; 
}
  • 循环语句 @for 指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。这个指令包含两种格式:@for varfrom<start>through<end>,或者@forvar from <start> through <end>,或者 @for var from to ,区别在于 through 与 to 的含义:当使用 through 时,条件范围包含 与 的值,而使用 to 时条件范围只包含 的值不包含 的值。另外,var可以是任何变量,比如var 可以是任何变量,比如 i; 和 必须是整数值。
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}
等同于
.item-1 {
  width: 2em;
}
.item-2 {
  width: 4em;
}
.item-3 {
  width: 6em;
}
  • while循环
$i: 5;
@while $i > 0 {
    .item-#{$i} {width: 2em * $i;}
    $i: $i - 2;
}
  • @each @each 指令的格式是 varin<list>,var in <list>, var 可以是任何变量名,比如 length或者length 或者 name,而 是一连串的值,也就是值列表:
@each $member in a, b, c, d {
.#{$member} {
    background-image: url("/image/#{$member}.jpg");
  }
}
  • function
@function double($n) {
  @return $n * 2;
}
#sidebar {
  width: double(5px);
}