Sass嵌套规则

嵌套组合不同于逻辑结构。使用SASS,我们可以在彼此合并多个CSS规则。如果使用多个选择器,那么可以使用一个选择在另一个创建复合选择器。

实例

下面的例子描述了SCSS文件嵌套的规则的使用:
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>嵌套规则 - www.xuhuhu.com</title>
   <link rel="stylesheet" type="text/css" href="style.css" />
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
   <div class="container">
   <h1>My First Heading</h1>
   <p>It is a CSS pre-processor which helps to reduce repetition with CSS and save the time. </p>
   <p>It is more stable and powerful CSS extension language.</p>
   <div class="box">
   <h1>My Second Heading</h1>
   <p>It is initially designed by Hampton Catlin and developed by Natalie Weizenbaum in 2016.</p>
   </div>
   </div>
</body>
</html>
接下来,创建文件style.scss。注意.scss扩展。

style.scss

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

 .box{
  h1{
        font-size: 25px;
        color:#E45456;
  }
  p{
       font-size: 25px;
       color:#3C7949;
  }
 }
}
可以告诉SASS监视文件,并使用下面的命令随时更新SASS文件来修改CSS:
sass --watch C:\Ruby22-x64\style.scss:style.css

接下来执行上面的命令,它会自动创建style.css文件,如下面的代码:

所产生的 style.css 如下:

style.css

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

输出结果

让我们来执行以下步骤,看看上面的代码工作:
  • 保存上述HTML代码内容到 nested_rules.html 文件。
  • 在浏览器中打开这个HTML文件,输出如下得到显示。



上一篇: Sass的使用 下一篇: Sass引用父选择器