【问题标题】:Sass @each and @if/else mixin snippet?Sass @each 和 @if/else 混合片段?
【发布时间】:2018-09-17 15:03:26
【问题描述】:

我是 Sass 的新手,我正在尝试获得这样的 CSS;

.heading-lg { 
font-size: 11.2rem;}

.heading-md { 
font-size: 11.2rem;}

.heading-sm { 
font-size: 11.2rem;}

这是我的 SCSS 代码。但是所有的 heading-xx 类都得到 11.2rem。谁能给我指路?非常感谢。

$font-size: 1.6rem;
$heading-size: .8rem;
$heading: lg md sm;
$heading-lg: lg;
$heading-md: md;
$heading-sm: sm;

@each $size in $heading {
    .heading-#{$size} {

        @if $heading-lg==lg {
            font-size: $font-size + $heading-size * (12);
        }
        @else if $heading-md==md {
            font-size: $font-size + $heading-size * (10);
        }
        @else {
            font-size: $font-size + $heading-size * (8);
        }
    }
}

【问题讨论】:

  • 你在寻找什么输出?

标签: css sass scss-mixins


【解决方案1】:

您应该使用$size 变量而不是$heading-lg。如上面您的代码,@each 中的$heading-lg 始终等于 lg,因此会导致您的问题。

@each $size in $heading {
    .heading-#{$size} {

        @if $size==lg {
            font-size: $font-size + $heading-size * (12);
        }
        @else if $size==md {
            font-size: $font-size + $heading-size * (10);
        }
        @else {
            font-size: $font-size + $heading-size * (8);
        }
    }
}

【讨论】:

    【解决方案2】:

    另一个好的解决方案是使用映射:也许它更具可读性(因为您立即关联键值)并且您不必在 @each 循环中使用 @if 语句:

    $font-size: 1.6rem;
    $heading-size: .8rem;
    
    $heading-list: (
      lg:12,
      md:10,
      sm:8
    );
    
    @each $key, $value in $heading-list {
      .heading-#{$key} {
        font-size: $font-size + $heading-size * ($value);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-19
      • 2015-09-05
      • 2012-09-06
      • 2012-01-06
      • 1970-01-01
      • 2018-09-11
      • 2012-11-13
      • 2014-02-19
      相关资源
      最近更新 更多