sass @for循环

2019-04-093891次阅读sass

在写样式的时候,估计你会写过这样有规律的样式:

.navWrap a {
  width: 94px;
  height: 45px;
  margin: 30px 0 0 48px;
  background: url(../images/nav.png) no-repeat; }

a.nav0 {
  background-position: 0 0px; }
  a.nav0:hover, a.nav0.cur {
    background-position: -94px 0px; }

a.nav1 {
  background-position: 0 -45px; }
  a.nav1:hover, a.nav1.cur {
    background-position: -94px -45px; }

a.nav2 {
  background-position: 0 -90px; }
  a.nav2:hover, a.nav2.cur {
    background-position: -94px -90px; }

a.nav3 {
  background-position: 0 -135px; }
  a.nav3:hover, a.nav3.cur {
    background-position: -94px -135px; }

a.nav4 {
  background-position: 0 -180px; }
  a.nav4:hover, a.nav4.cur {
    background-position: -94px -180px; }

在Sass中,我们可以使用@for循环来轻松实现。

.navWrap{
    a{
        width:94px;
        height:45px;
        @extend %fl;
        margin:30px 0 0 48px;
        @extend %fnone;
        background:url(../images/nav.png) no-repeat;
    }
}

@for $i from 0 through 4{
    a.nav#{$i}{
        background-position: 0 $i*-45px;
        &:hover,&.cur{
            background-position: -94px $i*-45px;
        }
    }
}

@for

sass中@for指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。这个指令包含两种格式:

  • @for $var from <start> through <end>
  • @for $var from <start> to <end>

区别在于 through 与 to 的含义:当使用 through 时,条件范围包含 <start> 与 <end> 的值,而使用 to 时条件范围只包含 <start> 的值不包含 <end> 的值。另外,$var 可以是任何变量,比如 $i;<start> 和 <end> 必须是整数值。

插值语句 #{}

通过 #{} 插值语句可以在选择器或属性名中使用变量

$name: foo;
$attr: border;
p.#{$name} {
  #{$attr}-color: blue;
}

编译为

p.foo {
  border-color: blue; }

#{} 插值语句也可以在属性值中插入 SassScript,大多数情况下,这样可能还不如使用变量方便,但是使用 #{} 可以避免 Sass 运行运算表达式,直接编译 CSS。

p {
  $font-size: 12px;
  $line-height: 30px;
  font: #{$font-size}/#{$line-height};
}

编译为

p {font: 12px/30px; }

 

上一篇: 触摸事件(touch)事件简述  下一篇: Google Chrome and ios Safari 对 HTTP 网站显示不安全警告  

sass @for循环相关文章