开发者

One-liner is SASS

In CSS I can do something like this:

.apple  { background-image: url('apple.png'); }
.orange { background-image: url('orange.png'); }
.pear   { background-image: url('pear.png'); }

but it seems in sass (not scss) the same would take up 6 lines? Is it possible to do a one-liner is sass for rules that only have one开发者_高级运维 property?


This isn't by any means meant to help you condense this code to one line, but to think of it from a different perspective.

In this post on The Sass Way titled "Sass control directives: @if, @for, @each and @while", I cover control directives in Sass. Here's a way to write your code using the @each directive.

$fruit-list: apple orange pear

=fruit
  @each $fruit in $fruit-list
    &.#{$fruit}
      background-image: url(#{$fruit}.png)

.fruit
  +fruit

Which outputs:

.fruit.apple {
  background-image: url(apple.png);
}
.fruit.orange {
  background-image: url(orange.png);
}
.fruit.pear {
  background-image: url(pear.png);
}

Using .scss we can make this a one liner, but at the cost of readability of the code:

$fruit-list: apple orange pear;

@mixin fruit { @each $fruit in $fruit-list { &.#{$fruit} { background-image: url(#{$fruit}.png); } } }

.fruit { @include fruit; }


Sass syntax is principally based on indentation and line breaks, so in Sass that would indeed be six lines (two per rule, excluding blank lines):

.apple
    background-image: url('apple.png')

.orange
    background-image: url('orange.png')

.pear
    background-image: url('pear.png')

As far as I've seen you can't condense those to one-liners in Sass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜