开发学院

您的位置:首页>教程>正文

教程正文

LESS 嵌套规则

LESS 嵌套规则

  它是一组CSS属性,允许使用一个类的属性到另一个类,并包括类名称作为其属性。在LESS中,你可以使用类或id选择同样的方式作为CSS样式声明混入。它可以存储多个值,并可以在必要时在代码中重用。

示例

<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文件,得到如下输出显示。

1-160113101040440.png