学习Sass中 @if...@else @for @while @each

一、条件判断 - @if @else

 示例: 

 @mixin blockOrHidden($boolean:true){
@if $boolean {
@debug "$boolean is #{$boolean}";
display: block;
}
@else {
@debug "$boolean is #{$boolean}";
display: none;
}
} .block {
@include blockOrHidden;//默认
} .hidden {
@include blockOrHidden(false);//为假
}

 输出:

 .block {
display: block; } .hidden {
display: none; }

二、 @for 循环

  两种方式:
      @for $i from <start> through <end>
      @for $i from <start> to <end>
      $i 表示变量; start 表示起始值; end 表示结束值;
    
      这两个的区别是关键字 through 表示包括 end 这个数,而 to 则不包括 end 这个数。
  示例:

 //使用 through 关键字的示例:
@for $i from 1 through 3 {
.item-#{$i} {
width: 2em * $i;
}
}

  输出:

 .item-1 {
width: 2em; } .item-2 {
width: 4em; } .item-3 {
width: 6em; }

  示例:

 //使用 to 关键字的示例:
@for $i from 1 to 3 {
.item-#{$i}#{1} {
width: 2em * $i;
}
}

  输出:

 .item-11 {
width: 2em; } .item-21 {
width: 4em; }

  例子:

 /*
for循环应用示例:
*/
$grid-prefix: span !default;
$grid-width: 60px !default;
$grid-gutter: 20px !default; %grid {
float: left;
margin-left: $grid-gutter / 2;
margin-right: $grid-gutter /2;
}
@for $i from 1 through 6 {
.#{$grid-prefix}#{$i} {
width: $grid-width * $i + $grid-gutter * ($i - 1);
@extend %grid;
}
}

  输出结果:

 /*
for循环应用示例:
*/
.span1, .span2, .span3, .span4, .span5, .span6 {
float: left;
margin-left: 10px;
margin-right: 10px; } .span1 {
width: 60px; } .span2 {
width: 140px; } .span3 {
width: 220px; } .span4 {
width: 300px; } .span5 {
width: 380px; } .span6 {
width: 460px; }

三、@while 循环

  示例:

 $types: 4;
$type-width: 20px; @while $types > 0 {
.while-#{$types} {
width: $type-width + $types;
}
$types: $types - 1;
}

  输出:

 /*
while 循环
*/
.while-4 {
width: 24px; } .while-3 {
width: 23px; } .while-2 {
width: 22px; } .while-1 {
width: 21px; }

四、@each 循环

  @each 循环就是去遍历一个列表,然后从列表中取出对应的值。
      @each 循环指令的形式: @each $var in <list>

  示例:

 $list: adam john wynn mason kuroir;//$list 是一个列表
@mixin author-images {
@each $author in $list {
.photo-#{$author} {
background: url("/images/avatars/#{$author}.png");
}
}
} .author-bio {
@include author-images;
}

  输出:

 .author-bio .photo-adam {
background: url("/images/avatars/adam.png"); }
.author-bio .photo-john {
background: url("/images/avatars/john.png"); }
.author-bio .photo-wynn {
background: url("/images/avatars/wynn.png"); }
.author-bio .photo-mason {
background: url("/images/avatars/mason.png"); }
.author-bio .photo-kuroir {
background: url("/images/avatars/kuroir.png"); }

学习 大漠老师 - Sass入门篇 笔记 http://www.w3cplus.com/

05-11 15:12