1-3 @for循环(上)
本节编程练习不计算学习进度,请电脑登录imooc.com操作

@for循环(上)

在制作网格系统的时候,大家应该对 .col1~.col12 这样的印象较深。在 CSS 中你需要一个一个去书写,但在 Sass 中,可以使用 @for 循环来完成。在 Sass 的 @for 循环中有两种方式:

@for $i from <start> through <end>
@for $i from <start> to <end>

这两个的区别是关键字 through 表示包括 end 这个数,而 to 则不包括 end 这个数。

如下代码,先来个使用 through 关键字的例子:

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

编译出来的 CSS:

.item-1 {
  width: 2em;
}

.item-2 {
  width: 4em;
}

.item-3 {
  width: 6em;
}

再来个 to 关键字的例子:

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

编译出来的 CSS:

.item-1 {
  width: 2em;
}

.item-2 {
  width: 4em;
}

 

任务

小伙伴们,现在让我们来练习一下@for循环的用法吧!

  1. // ----
  2. // Sass (v3.4.12)
  3. // Compass (v1.0.3)
  4. // ----
  5.  
  6.  
  7.  
  8.  
  9. //through
  10. @for $i from 1 through 3 {
  11. .item-#{$i} { width: 2em * $i; }
  12. }
  13.  
  14.  
  15.  
  16. //to
  17. @for $i from 1 to 3 {
  18. .item-#{$i} { width: 2em * $i; }
  19. }
下一节