LESS - 受保护的命名空间

描述

当将保护应用于命名空间时,仅当保护条件返回 true 时才使用由命名空间定义的混合。命名空间保护类似于混合上的保护。

示例

以下示例演示了在 LESS 文件中使用受保护的命名空间

<html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
      <title>Guarded Namespaces</title>
   </head>

   <body>
      <h2>Welcome to Tutorialspoint</h2>
      <p>This will paragraph be displayed red, when (@color = blue) in style.less 
      and when color is other than blue, then this paragraph will be default black.</p>
   </body>
</html>

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

style.less

@import "http://www.tutorialspoint.com/less/lib.less";
#namespace when (@color = blue) {
   .mixin() {
      color: red;
   }
}

p {
   #namespace .mixin();
}

以下代码将从路径 https://www.tutorialspoint.com/less/lib.lesslib.less 文件导入到 style.less 中 −

lib.less

@color: blue;

您可以使用以下命令将 style.less 编译为 style.css

lessc style.less style.css

执行上述命令;它将使用以下代码自动创建 style.css 文件 −

style.css

p {
   color: red;
}

输出

按照以下步骤查看上述代码的工作原理 −

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

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

LESS Guarded Namespaces

less_mixins.html