SASS - 适用于h1-h6风格

时间:2016-01-19 13:06:10

标签: css sass

我有这样的SCSS风格,我想使用SCSS中的@for来提高效率。

到目前为止:

@for $i from 1 through 6 {
  h#{$i} {
    $size: {$i} * 1.4;
    @include font-size($size);
  }
}

注意:不要介意大小的计算,它只是用于测试

但语法不对。

预期输出

h1 {
  @include font-size(3.2);
}

h2 {
  @include font-size(2.4);
}

h3 {
  @include font-size(1.8);
}

h4 {
  @include font-size(1.6);
}

h5 {
  @include font-size(1.3);
}

h6 {
  @include font-size(1.2);
}

1 个答案:

答案 0 :(得分:4)

主要问题是h1大小越来越大(因为您逐渐使用$i)。您可以使用公式7 - $i减少h值大小来逃避这种情况。

@for $i from 1 through 6 {
    h#{7 - $i} {
        fontsize: $i * 1.4em;
    }
}

这里的输出是:

h6 { font-size:1.4em }
h5 { font-size:2.8em }
h4 { font-size:4.2em }
h3 { font-size:5.6em }
h2 { font-size:7em }
h1 { font-size:8.4em }

这似乎有道理。你得到的原始错误是:

Invalid CSS after "$size:": expected expression (e.g. 1px, bold), was "{$i} * 1.4;"

因为您可以简单地使用$i作为数字而无需特殊标记。

要获得与您的问题相匹配的数字,您实际上应该找到一种方法来计算它们 - 并且您在上面显示的数字不是模式,因此它们不是数学上的可控。这是你能做的:

@for $i from 1 through 6 {
    h#{7 - $i} {
        fontsize: 3.4em / 6 * $i;
    }
}

无法像您的问题那样在数学上计算这个问题的原因是:h1 - h2 = .6emh2 - h3 = .6emh3 - h4 = .2em =>最后一个不符合任何特定模式。