嵌套是Sass/Scss非常好用的特性,它们不仅大大减少了你的编写量,而且通过视觉上的缩进使你编写的样式结构更加清晰,更易于阅读和开发。

基础使用

修改 index.html 代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="assets/css/common.css">
</head>
<body>
<div class="wrap">
    <div class="article">
        <h1>Scss的基础用法</h1>
        <p>你好 Scss</p>
    </div>
    <aside>很简单哦,我学会了</aside>
</div>
</body>
</html>

修改 common.scss

.wrap {
  background-color: #fff;
  font-size: 18px;

  h1 {
    color: #333
  }

  p {
    margin-bottom: 1.4em
  }

  aside { background-color: #EEE }
}

编译后

.wrap {
  background-color: #fff;
  font-size: 18px;
}
.wrap h1 {
  color: #333;
}
.wrap p {
  margin-bottom: 1.4em;
}
.wrap aside {
  background-color: #EEE;
}

父选择器 &

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="assets/css/common.css">
</head>
<body>
<div class="wrap">
    <div class="article">
        <a href="#">我是 Scss,请点我</a>
    </div>
</div>
</body>
</html>
.article a {
  color: blue;

  :hover {
    color: pink
  }
}

编译后

.article a {
  color: blue;
}

/*注意 a 后面的空格*/
.article a :hover {
  color: pink;
}

上述代码实现的效果是:当鼠标放上去后,样式无变化,这是因为 hover 是 article 的一个后代元素。那么想让它实现鼠标放上去显示不同样式,改如何实现呢?

.article a {
  color: #333;

  &:hover {
    color: pink
  }
}

编译后

.article a {
  color: #333;
}
/*注意 a 后面没有空格了*/
.article a:hover {
  color: pink;
}

子元素选择器 >:选择一个元素的直接子元素

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="assets/css/common.css">
</head>
<body>
<div class="wrap">
    <div class="article">
        <section>123</section>
        <section>456</section>
        <p>789</p>
    </div>
</div>
</body>
</html>

.article {
  > section {
    background: #eee
  }
}

编译后

.article > section {
  background: #eee;
}

群组嵌套

.container {
  h1, h2, h3 {margin-bottom: .8em}
}

编译后

.container h1, .container h2, .container h3 {
  margin-bottom: 0.8em;
}

属性嵌套

nav {
  border: {
    style: solid;
    width: 1px;
    color: #ccc;
  }
}

编译后

nav {
  border-style: solid;
  border-width: 1px;
  border-color: #ccc;
}

已添加到喜欢了