Reputation:
I'm trying to come up with a way to simplify some SCSS attribute selectors. What I end up with is:
[data-attr="opt1"] { ... }
[data-attr="opt2"] { ... }
[data-attr="opt3"] { ... }
What I'm hoping for is to be able to write something closer to:
[data-attr]
&="opt1" { ... }
&="opt2" { ... }
&="opt3" { ... }
via a mixin, or whatever. Can't come up with a solution though. Any clever ideas?
Upvotes: 0
Views: 476
Reputation: 123387
I've come to this idea:
@mixin attrVal($value) {
$attr: str-slice(#{&}, 2, -2); // $attr = "data-attr"
@at-root {
[#{$attr}="#{$value}"] {
@content;
}
}
}
[data-attr] {
@include attrVal('opt1') { width: 10px; }
@include attrVal('opt2') { width: 20px; }
@include attrVal('opt3') { width: 30px; }
}
Output (tested on sassmeister.com)
[data-attr="opt1"] { width: 10px; }
[data-attr="opt2"] { width: 20px; }
[data-attr="opt3"] { width: 30px; }
For this specific example there's no that huge simplification, but with this approach you're actually decoupling the attribute name from its value (in the aim of code reuse).
Upvotes: 1