scss语法进阶

  • 表达式

变量写法 $variable , 变量当作字符使用 #{$variable}

@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

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

@each

@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

@while

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

include 调用

@mixin button {  
    font-size: 1em;  
    padding: 0.5em 1.0em;  
    text-decoration: none;  
    color: #fff;  
}

.button-green {  
    @include button;  
    background-color: green;  
}

@include button;

带参数的写法

@mixin button($background) {  
    font-size: 1em;  
    padding: 0.5em 1.0em;  
    text-decoration: none;  
    color: #fff;  
    background: $background;  
}
.button-green { 
   @include button(green); 
}

@content 方式,添加不同的样式

@mixin button {  
    font-size: 1em;  
    padding: 0.5em 1.0em;  
    text-decoration: none;  
    color: #fff;  
    @content;  
}

.button-green {  
    @include button {  
        background: green  
    }
}

用在兼容写法的时候,很方便

@mixin transform($property) {
  -webkit-transform: $property;
      -ms-transform: $property;
          transform: $property;
}

.box { @include transform(rotate(30deg)); }

多个参数,可以使用写法

@mixin colors($text, $background, $border) {
  color: $text;
  background-color: $background;
  border-color: $border;
}

$values: #ff0000, #00ff00, #0000ff;
.primary {
  @include colors($values...);
}
  • 函数写法
$grid-width: 40px;
$gutter-width: 10px;

@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { width: grid-width(5); }

输出:

#sidebar {
  width: 240px; }
  • import用法
$family: unquote("Droid+Sans");
@import url("http://fonts.googleapis.com/css?family=#{$family}");
@import "foo.scss";

等同于

@import "foo";
@media screen {
  .sidebar {
    @media (orientation: landscape) {
      width: 500px;
    }
  }
}

编译结果:

@media screen and (orientation: landscape) {
  .sidebar {
    width: 500px; } }
  • 运算符
p {
  font: 10px/8px;             // Plain CSS, no division
  $width: 1000px;
  width: $width/2;            // Uses a variable, does division
  width: round(1.5)/2;        // Uses a function, does division
  height: (500px/2);          // Uses parentheses, does division
  margin-left: 5px + 8px/2px; // Uses +, does division
}

也可以用在文本中

p:before {
  content: "I ate #{5 + 10} pies!";
}