SASS and Data Attribute Selecting and Nesting -


i apply style elements data attribute product specific products.

is there way this?

// sass [data-product] {   color: #000;   &[="red"] {   // <- line     color: #f00;   } } 

prior sass 3.4, not possible @ all. deal-breaking features here ability store current selector variable , ability split string (though later created via sassscript functions).

@mixin append-attr($x) {     $sel: &;     $collector: ();      @for $i 1 through length($sel) {         $s: nth($sel, $i);         $last: nth($s, -1);         @if str-slice($last, -1) == "]" {             // if bare attribute no value, $offset -1, otherwise -2             $offset: -1;             $current-x: $x;              @if str-slice($last, -2) == '"]' {                 // attribute has value, need adjust offset                 $offset: -2;             } @else {                 // no attribute value, add equals , quotes                 $current-x: '="' + $x + '"';             }             $last: str-slice($last, 1, $offset - 1) + $current-x + str-slice($last, $offset);             $collector: append($collector, set-nth($s, -1, $last), comma);         } @else {             // following line append $x non-attribute selector             $collector: append($collector, selector-append($s, $x), comma);             // following line not change non-attribute selector @             //$collector: append($collector, $s, comma);         }     }      @at-root #{$collector} {         @content;     } } 

usage:

[data-product] {     color: white;      @include append-attr("red") {         color: red;          @include append-attr('-green') {             color: green;         }     } }  [one], [two] {     color: orange;      @include append-attr('alpha') {         color: yellow;     } }  [test], .test {     @include append-attr('-one') {         color: red;     } }  .bar input[min] {     @include append-attr('5') {         background: yellow;     } } 

output:

[data-product] {   color: white; } [data-product="red"] {   color: red; } [data-product="red-green"] {   color: green; }  [one], [two] {   color: orange; } [one="alpha"], [two="alpha"] {   color: yellow; }  [test="-one"], .test-one {   color: red; }  .bar input[min="5"] {   background: yellow; } 

related: modifying middle of selector in sass (adding/removing classes, etc.)


Comments