LESS - 嵌套规则

描述

它是一组CSS属性,允许将一个类的属性用于另一个类,并包含类名作为其属性.在LESS中,您可以使用类或id选择器以与CSS样式相同的方式声明mixin.它可以存储多个值,并且可以在必要时在代码中重用.

示例

以下示例演示了在LESS中使用嵌套规则file :

<html>
   <head>
      <title>Nested Rules</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
   </head>
   
   <body>
      <div class = "container">
         <h1>First Heading</h1>
         <p>LESS is a dynamic style sheet language that extends the capability of CSS.</p>
         <div class = "myclass">
            <h1>Second Heading</h1>
            <p>LESS enables customizable, manageable and reusable style sheet for web site.</p>
         </div>
      </div>
   </body>
</html>

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

style.less

.container {
   h1 {
      font-size: 25px;
      color:#E45456;
   }
   p {
      font-size: 25px;
      color:#3C7949;
   }

   .myclass {
      h1 {
         font-size: 25px;
         color:#E45456;
      }
      p {
         font-size: 25px;
         color:#3C7949;
      }
   }
}

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

lessc style.less style.css

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

style.css

.container h1 {
   font-size: 25px;
   color: #E45456;
}

.container p {
   font-size: 25px;
   color: #3C7949;
}

.container .myclass h1 {
   font-size: 25px;
   color: #E45456;
}

.container .myclass p {
   font-size: 25px;
   color: #3C7949;
}

输出

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

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

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

较少的嵌套规则