hashtagrik hashtagrik - 4 months ago 19
Sass (Sass) Question

Nested data-toggle with SASS

I was wondering if it was possible to nest data-toggle in SASS.
Say I have some buttons to make which are the same width and height but the color of each is button is different.

Would it be possible to make them like:

[data-toggle]{
width:150px;
height:50px;
&=result{
background:green;
}
&=create{
background:red;
}
}

Answer

It's not possible to nest the selectors in the manner that you've suggested.

One solution is to create a Sass map of data-toggle values to background-colors, then use an @each loop to iterate over the key-value pairs:

// Base styling for elements with the [data-toggle] attribute
[data-toggle] {
  width: 150px;
  height: 50px;  
}

// Generate declarations for colored toggles
$data-toggle-colors: (
  'result': green,
  'create': red
);

@each $color in $data-toggle-colors {
  $key:   nth($color, 1);
  $value: nth($color, 2);

  [data-toggle=#{$key}] {
    background-color: $value;
  }
}

Codepen: https://codepen.io/anon/pen/Lkgxvv