2014-10-09 56 views
0

我有一组不同颜色的图标,每种颜色都与CSS类声明的不同状态一起使用。例如,<span class="icon icon--app"><span>给出了一个灰色的应用程序图标,而<span class="icon icon--app icon__light icon__selected"><span>给出了一个白色的应用程序图标。SASS规则重用

以下代码是在SCSS中编写的。

span.icon { 
    display: inline-block; 
    width: 32px; 
    height: 32px; 

    &.icon--app { 
     background: url(../images/app_gray.png); 

     &.icon__selected { 
      background: url(../images/app.png); 
     } 

     &.icon__light { 
      background: url(../images/app_gray.png); 

      &.icon__selected { 
       background: url(../images/app_white.png); 
      } 
     } 
    } 

    &.icon--device { 
     background: url(../images/device_gray.png); 

     &.icon__selected { 
      background: url(../images/device.png); 
     } 

     &.icon__light { 
      background: url(../images/device_gray.png); 

      &.icon__selected { 
       background: url(../images/device_white.png); 
      } 
     } 
    } 
} 

的问题是,还有很长的CSS规则列表如上,这股有很多相似之处的appdevice等图标。我想知道是否可以使用SASS来简化这些CSS规则?

+1

你有研究的CSS来看看它是否产生你期待的样式?我怀疑它的产生超过了必要。这个问题可能更适合CodeReview.SE(你应该可以请求一个mod让它转移)。 – cimmanon 2014-10-09 02:48:25

+0

从这段代码中告诉你的意图有点难。我编译了你的SASS,并生成了[这个CSS](https://gist.github.com/abitdodgy/297d063a41d6f1d4614a)。这里没有太多的重复。只是几个背景声明。虽然你可以把它封装在一个mixin中来减少类型声明。 – Mohamad 2014-10-09 02:53:13

回答

2

我为您创建一个混合:

@mixin icon($type) { 
    &.icon--#{$type} { 
    background: url(../images/#{$type}_gray.png); 

    &.icon__selected { 
     background: url(../images/#{$type}); 
    } 

    &.icon__light { 
     background: url(../images/#{$type}); 

     &.icon__selected { 
     background: url(../images/#{$type}_white.png) 
     } 
    } 
    } 
} 

span.icon { 
    display: inline-block; 
    width: 32px; 
    height: 32px; 

    @include icon(app); 

    @include icon(device); 
} 
4

我觉得你可以在萨斯使用mixin

例如

@mixin icon($type) { 
    .icon-#{$type} { 
     background: url(../images/#{$type}_gray.png); 
    } 
} 

@include icon(app); 
@include icon(device); 
+0

Upvote为我的一个类似mixin的声明! – 2014-10-09 02:56:52

+0

@hedgerh而且也是一个极其相似的答案时间! :) – 2014-10-09 02:58:59