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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With