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.