Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner is SASS

Tags:

css

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?

like image 731
jhchen Avatar asked Dec 28 '25 02:12

jhchen


1 Answers

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; }
like image 158
Adam Stacoviak Avatar answered Dec 30 '25 17:12

Adam Stacoviak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!