Function to dynamically create classes from lists

前端 未结 2 2012
悲哀的现实
悲哀的现实 2020-12-12 03:04

Im fairly new to SASS and I\'m confused by the way lists work. I have a multidimensional list like this:

$stylethemes: {
  (15, bold, red),
  (12, normal, bl         


        
2条回答
  •  北海茫月
    2020-12-12 03:59

    The code to produce the desired results would look like this:

    $stylethemes: (
      (15, bold, red),
      (12, normal, blue)
    );
    
    @for $i from 1 through length($stylethemes) {
      .theme#{$i} {
        font-size: nth(nth($stylethemes, $i), 1);
        font-weight: nth(nth($stylethemes, $i), 2);
        color: nth(nth($stylethemes, $i), 3);
      }
    }
    

    However, you'll find this isn't particularly flexible. You're better off using mappings for the property/values so that you don't have to guarantee a specific order:

    $stylethemes: (
      (font-size: 15, font-weight: bold, color: red),
      (font-size: 12, font-weight: normal, color: blue)
    );
    
    @for $i from 1 through length($stylethemes) {
      .theme#{$i} {
        @each $prop, $val in nth($stylethemes, $i) {
          #{$prop}: $val;
        }
      }
    }
    

    Or

    $stylethemes: (
      theme1: (font-size: 15, font-weight: bold, color: red),
      theme2: (font-size: 12, font-weight: normal, color: blue)
    );
    
    @each $theme, $properties in $stylethemes {
      .#{$theme} {
        @each $prop, $val in $properties {
          #{$prop}: $val;
        }
      }
    }
    

提交回复
热议问题