Sass @each

通过@each规则,可以轻松地为列表(List)中的每个元素或映射(Map)中的每个元素对发出样式或计算代码。它非常适合重复的样式,它们之间只有一些变化。它通常是 @each <variable> in <expression> { ... },其中表达式返回一个列表(List)。依次为列表(List)中的每个元素计算块,并将其分配给给定的变量名称。

SCSS


$sizes: 40px, 50px, 80px;

@each $size in $sizes {
  .icon-#{$size} {
    font-size: $size;
    height: $size;
    width: $size;
  }
}

编译为 CSS 结果:

CSS

.icon-40px {
  font-size: 40px;
  height: 40px;
  width: 40px;
}

.icon-50px {
  font-size: 50px;
  height: 50px;
  width: 50px;
}

.icon-80px {
  font-size: 80px;
  height: 80px;
  width: 80px;
}

使用映射(Map)

语法:@each <variable>, <variable> in <expression> { ... }

SCSS

$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");

@each $name, $glyph in $icons {
  .icon-#{$name}:before {
    display: inline-block;
    font-family: "Icon Font";
    content: $glyph;
  }
}

编译为 CSS 结果:

CSS

@charset "UTF-8";
.icon-eye:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-start:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-stop:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

解构

语法: @each <variable...> in <expression> { ... }

SCSS

$icons:
  "eye" "\f112" 12px,
  "start" "\f12e" 16px,
  "stop" "\f12f" 10px;

@each $name, $glyph, $size in $icons {
  .icon-#{$name}:before {
    display: inline-block;
    font-family: "Icon Font";
    content: $glyph;
    font-size: $size;
  }
}

编译为 CSS 结果:

CSS

@charset "UTF-8";
.icon-eye:before {
  display: inline-block
  font-family: "Icon Font";
  content: "";
  font-size: 12px;
}

.icon-start:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
  font-size: 16px;
}

.icon-stop:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
  font-size: 10px;
}

Captcha Code

0 笔记

分享笔记

Inline Feedbacks
View all notes