Sass - @if 指令



描述

@if 指令接受 SassScript 表示式,並且在表示式的結果除 falsenull 以外時使用巢狀樣式。

語法

@if expression {  //CSS codes are written here }

示例

以下示例演示了在 SCSS 檔案中使用 @if 指令:-

<html>
   <head>
      <title>Control Directives & Expressions</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css"/>
   </head>

   <body>
      <div class = "container">
         <h2>Example for Control Directive & Expressions</h2>
         <p>SASS stands for Syntactically Awesome Stylesheet. </p>
      </div>
   </body>
</html>

接下來,建立檔案 style.scss

style.scss

p {
   @if 10 + 10 == 20   { border: 1px dotted;   }
   @if 7 < 2     { border: 2px solid;  }
   @if null    { border: 3px double; }
}

你可以讓 SASS 監視檔案並在 SASS 檔案發生更改時更新 CSS,方法是使用以下命令:-

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

接下來,執行上述命令;它將自動建立 style.css 檔案,其中包含以下程式碼:-

style.css

p {
   border: 1px dotted; 
}

輸出

讓我們執行以下步驟,瞭解上面給出的程式碼如何工作:-

  • 在上給定的 html 程式碼儲存在 @if_directive.html 檔案中。

  • 在瀏覽器中開啟此 HTML 檔案,將會顯示如下輸出

Sass Control Directives & Expressions
sass_control_directives_expressions.htm
廣告
© . All rights reserved.