【问题标题】:Generate list of classes from SCSS list从 SCSS 列表生成类列表
【发布时间】:2019-12-05 13:56:21
【问题描述】:

问题:是否可以使用 SCSS 列表生成多个类而不重复属性?

关键是通过一个名称列表 ($svgs) 来保持文件易于维护,然后可以将其用于类或变量(参见下面的示例,$svg)。这个列表实际上要大得多。

请注意,我不能使用 .box i[class*=".icon-"] 或类似的选择器,因为还有其他元素会受到影响。

这是当前的 SCSS,它可以工作,但会创建臃肿的 CSS。 .

$svgs: cancel, danger, exit;

@each $svg in $svgs {
  .box i.icon- {
    &#{$svg} {
      background-image: url($svg + '.svg');

      height: 24px;
      width: 24px;
      background-repeat: no-repeat;
      background-size: contain;
    }
  }
}

结果 CSS 为:

.box i.icon-cancel {
  background-image: url("cancel.svg");
  height: 24px;
  width: 24px;
  background-repeat: no-repeat;
  background-size: contain;
}

.box i.icon-danger {
  background-image: url("danger.svg");
  height: 24px;
  width: 24px;
  background-repeat: no-repeat;
  background-size: contain;
}

.box i.icon-exit {
  background-image: url("exit.svg");
  height: 24px;
  width: 24px;
  background-repeat: no-repeat;
  background-size: contain;
}

所需的 CSS:

.box i.icon-cancel, .box i.icon-danger, .box i.icon-exit {  
  height: 24px;
  width: 24px;
  background-repeat: no-repeat;
  background-size: contain;
}

.box i.icon-cancel {
  background-image: url("cancel.svg");
}

.box i.icon-danger {
  background-image: url("danger.svg");
}

.box i.icon-exit {
  background-image: url("exit.svg");
}

【问题讨论】:

    标签: sass


    【解决方案1】:

    要获得此结果,您可以使用 @extendplaceholder selector

    $svgs: cancel, danger, exit;
    
    %svg-styles {
      height: 24px;
      width: 24px;
      background-repeat: no-repeat;
      background-size: contain;
    }
    
    @each $svg in $svgs {
      .box i.icon- {
        &#{$svg} {
          @extend %svg-styles;
          background-image: url($svg + '.svg');
        }
      }
    }
    

    【讨论】:

    • 这是一个很棒的组合!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多