Sass @each指令

2018-12-30 18:15 更新

描述

在@each中,定义了一个变量,其中包含列表中每个项目的值。

语句

@each $var in <list or map>

下面简要解释语法。

  • $var: 它表示变量的名称。 @each规则将$var设置到列表中的每个项目,并使用值$var输出样式。

  • <list or map>: 这些是SassScript表达式,将返回列表或映射。

例子

下面的例子演示了使用@each指令:

<html>
<head>
   <title>Control Directives & Expressions</title>
   <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
   <p class="p_red">This is line one.</p>
   <p class="p_green">This is line two.</p>
   <p class="p_yellow">This is line three.</p>
   <p class="p_blue">This is line four.</p>
</body>
</html>

接下来,创建文件style.scss。

style.scss

@each $color in red, green, yellow, blue {
  .p_#{$color} {
    background-color: #{$color};
  }
}

您可以通过使用以下命令让SASS查看文件,并在SASS文件更改时更新CSS:

sass --watch C:\ruby\lib\sass\style.scss:style.css

接下来执行上面的命令,它将自动创建style.css文件用下面的代码:

style.css

.p_red {
  background-color: red; }

.p_green {
  background-color: green; }

.p_yellow {
  background-color: yellow; }

.p_blue {
  background-color: blue; }

输出

让我们执行以下步骤,看看上面的代码如何工作:

  • 将上述html代码保存在@ each.html文件中。

  • 在浏览器中打开此HTML文件,将显示如下输出。

Sass Control Directives & Expressions
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号