从SCSS列表生成类列表

时间:2019-12-05 13:56:21

标签: sass

问题:是否可以使用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");
}

1 个答案:

答案 0 :(得分:0)

要获得此结果,您可以将@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');
    }
  }
}
相关问题