@each with @include mixin

时间:2016-10-28 17:48:27

标签: css fonts sass google-webfonts

我有30个字体的下拉列表,我希望下拉列表的字体也显示Google字体(当然是为了直观表示!)示例文字。

我有带ID的HTML,例如:font-oswald-lightfont-oswald-regfont-oswald-bold

使用@each指令,我想做类似的事情:

@each $font-name, $font-mixin in (lato, Lato-Light),
                                  (open_sans, Open_Sans-Light),
                                  (oswald, Oswald-Light),
                                  (raleway, Raleway-Light),
                                  (roboto, Roboto-Light),
                                  (source_sans_pro, Source_Sans_Pro-Light),
                                  (ubuntu, Ubuntu-Light) {
  #font-#{$font-name}-light {
    @include #{$font-mixin};
  }
}

创建font-family:

@import url('https://fonts.googleapis.com/css?family=......)

@mixin Lato-Light {
  font-family: 'Lato', sans-serif;
  font-weight: 300;
  font-style: normal;
}

@mixin Lato-Reg {
  font-family: 'Lato', sans-serif;
  font-weight: 400;
  font-style: normal;
}

@mixin Lato-Bold {
  font-family: 'Lato', sans-serif;
  font-weight: 700;
  font-style: normal;
}

然而,@ each不喜欢里面的@include来显示font-family。我没有使用任何库(波本威士忌,指南针等)来创建font-face()。

我的问题是:什么是动态创建@each字体ID列表的方法,以便在尝试@include系列时不会出错?

1 个答案:

答案 0 :(得分:0)

#font-#{$font-name}-light {
  @include #{$font-mixin};
}

首先,这段代码无法运作。插值在Sass中不起作用。 Sass期望在@include关键字后面有 标识符 ,当它遇到此代码时,它会将$font-mixin评估为变量所代表的值,并且&它只是一个。 Sass不会将 解释为 标识符

其次,您不需要为每种字体创建mixin。这种方法不灵活,甚至不易维护。

我建议使用一个mixin来循环fonts map以动态生成所需的CSS。

$fonts-list:(
  lato-light: ("Lato", sans-serif) 300 normal,
  lato-reg: ("Lato", sans-serif) 400 normal,
  lato-bold: ("Lato", sans-serif) 700 normal,
  oswald-light: ("Oswald", sans-serif) 200 normal,
  oswald-reg: ("Oswald", sans-serif) 400 normal
);


@mixin fonts($family, $weight, $style) {
  font-family: $family;
  font-weight: $weight;
  font-style: $style;
}

@each $font, $attributes in $fonts-list {
  #font-#{$font} {
    @include fonts(nth($attributes, 1), nth($attributes, 2), nth($attributes, 3));
  }
}

编译的CSS看起来像这样

#font-lato-light {
  font-family: "Lato", sans-serif;
  font-weight: 300;
  font-style: normal;
}

#font-lato-reg {
  font-family: "Lato", sans-serif;
  font-weight: 400;
  font-style: normal;
}

#font-lato-bold {
  font-family: "Lato", sans-serif;
  font-weight: 700;
  font-style: normal;
}

#font-oswald-light {
  font-family: "Oswald", sans-serif;
  font-weight: 200;
  font-style: normal;
}

#font-oswald-reg {
  font-family: "Oswald", sans-serif;
  font-weight: 400;
  font-style: normal;
}

您可以决定使用多个 字体映射 来存储基于变体的字体,即$fonts-light,它存储所有 光变化 字体$fonts-reg,它存储字体的所有 常规变体 ...然后您可以循环浏览他们每个人都是一样的。这一切都取决于你喜欢的结构。我希望这有帮助

相关问题