Sass-@each 指令



說明

@each 中,定義了一個變數來儲存列表中每個專案的值。

語法

@each $var in <list or map>

語法如下所示,簡單解釋一下:

  • $var - 表示變數名稱。@each 規則將 $var 設定為列表中的每個專案,並使用 $var 的值輸出樣式。

  • <list or map> - 這是 SassScript 表示式,將返回一個 listmap

示例

以下示例演示瞭如何使用 @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
sass_control_directives_expressions.htm
廣告
© . All rights reserved.