- Sass 教程
- Sass-主頁
- Sass-概述
- Sass-安裝
- Sass-語法
- 使用 Sass
- Sass-CSS 擴充套件
- Sass-註釋
- Sass-指令碼
- Sass-@-規則和指令
- 控制指令和表示式
- Sass-混合指令
- Sass-函式指令
- Sass-輸出樣式
- 擴充套件 Sass
- 有用的 Sass 資源
- Sass-面試問題
- Sass-快速指南
- 有用的 Sass 資源
- Sass-討論
Sass-@each 指令
說明
在 @each 中,定義了一個變數來儲存列表中每個專案的值。
語法
@each $var in <list or map>
語法如下所示,簡單解釋一下:
$var - 表示變數名稱。@each 規則將 $var 設定為列表中的每個專案,並使用 $var 的值輸出樣式。
<list or map> - 這是 SassScript 表示式,將返回一個 list 或 map。
示例
以下示例演示瞭如何使用 @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.htm
廣告