在SASS中使用@each制作嵌套地图

时间:2014-08-08 02:04:10

标签: sass

我有以下SASS正常工作,我现在用它来尝试让媒体查询更改DRYer比现在更适合我。针对一些模块化或总结。

$perfect-fourth: 1.3333333333333;

$ma-base: 16;
$grandma-base: 18;

$type-ratio: $perfect-fourth;

$font-sizes: (
    ma: (
        xsmall: round($ma-base/$type-ratio),
        small: round($ma-base),
        medium: round($ma-base*$type-ratio),
        large: round($ma-base*$type-ratio*$type-ratio),
        xlarge: round($ma-base*$type-ratio*$type-ratio*$type-ratio)
    ),
    grandma: (
        xsmall: round($grandma-base/$type-ratio),
        small: round($grandma-base),
        medium: round($grandma-base*$type-ratio),
        large: round($grandma-base*$type-ratio*$type-ratio),
        xlarge: round($grandma-base*$type-ratio*$type-ratio*$type-ratio)
    )
    // With several more lists
);

@function size($size, $family-member:ma) {
    @return map-get(map-get($font-sizes, $family-member), $size);
}

我的想法是,我会打电话,例如:

// 'rem' and 'media' are functions I have defined elsewhere
@include media($ma) {
  p { font-size: rem(size(medium));
}
@include media($grandma) {
  p { font-size: rem(size(medium, grandma));
}

我想弄清楚的是如何生成那些嵌套的地图并将它们放在$ sizes中。这就是我现在所拥有的:

$family-sizes: (grandkid:14, kid:16, ma:16, grandma:18);

$font-sizes : (
    @each $family-member, $size in $family-sizes {
        $family-member: (
            xsmall: round($size/$family-ratio),
            small: round($size),
            medium: round($size*$family-ratio),
            large: round($size*$family-ratio*$family-ratio),
            xlarge: round($size*$family-ratio*$family-ratio*$family-ratio)  
        )
    };
);

@function size($size, $family-member:ma) {
    @return map-get(map-get($font-sizes, $family-member), $size);
}

遗憾的是,这不起作用,我尝试的其他方法都没有奏效。 @each指令似乎正在起作用,但我仍然坚持将这些列表放在一个列表中。任何提示或想法?我认为地图合并可能会有所帮助,但我不确定如何实施它。

1 个答案:

答案 0 :(得分:1)

使用@each(或任何指令)不会返回值,因此无法存储到变量中。您需要使用一个适用于映射(或列表)的函数以编程方式附加映射,就像您使用普通列表一样:

$font-sizes: ();
@each $family-member, $size in $family-sizes {
    $font-sizes: map-merge($font-sizes, ($family-member: (
        xsmall: round($size/$family-ratio),
        small: round($size),
        medium: round($size*$family-ratio),
        large: round($size*$family-ratio*$family-ratio),
        xlarge: round($size*$family-ratio*$family-ratio*$family-ratio)  
    )));
}

现在,如果您正在寻找一种更简单的方法,我建议您利用Modular Scale库。

@import "modular-scale";

$font-base: 16px !default;
$font-scale: 1.5 !default;
// shouldn't need to modify these
$font-keywords: (xsmall: -2, small: -1, medium: 0, large: 1, xlarge: 2);
$fractional-units: em, rem, unquote('%'); // add as needed

@function size($keyword, $base: $font-base, $scale: $font-scale) {
  $size: ms(map-get($font-keywords, $keyword), $base, $scale);
  @return if(index($fractional-units, unit($base)), $size, round($size));
}

.foo {
  a: size(medium);
  b: size(small);
  c: size(large, 1em);
  d: size(xlarge, 1em);
  f: size(xsmall, size(small));
}

http://sassmeister.com/gist/45c07f9aa6b2daa984be