sass学习笔记(2)

1.父选择器的标识符&

下面这种sass就无法工作
article a { color: blue; :hover { color: red } }.

解决的方法就是使用一个特殊的sass选择器&,如下所示:

article a {
  color: blue;
  &:hover { color: red }
}

/*编译后*/
article a { color: blue }
article a:hover { color: red }

可以在父选择器之前添加选择器

#content aside {
  color: red;
  body.ie & { color: green }
}

/*编译后*/
#content aside {color: red};
body.ie #content aside { color: green }

2.群组选择器的嵌套

下面的修改将浪费大量的时间在写选择器上

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

sass 的嵌套在某些特定的场景下非常有用,当sass解开一个群组选择器规则内嵌规则时,它会把每一个内嵌选择器的规则都正确的解出来:

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

3.子组合选择器和同层组合选择器:>、+和~

article {
  ~ article { border-top: 1px dashed #ccc }
  > section { background: #eee }
  dl > {
    dt { color: #333 }
    dd { color: #555 }
  }
  nav + & { margin-top: 0 }
}

/*sass会如你所愿地将这些嵌套规则一一解开组合在一起:*/

article ~ article { border-top: 1px dashed #ccc }
article > footer { background: #eee }
article dl > dt { color: #333 }
article dl > dd { color: #555 }
nav + article { margin-top: 0 }

4.嵌套属性

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

嵌套属性的规则是这样的:把属性名从中划线-的地方断开,在根属性后边添加一个冒号:,紧跟一个{ }块,把子属性部分写在这个{ }块中。就像css选择器嵌套一样,sass会把你的子属性一一解开,把根属性和子属性部分通过中划线-连接起来,最后生成的效果与你手动一遍遍写的css样式一样:

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

对于属性的缩写形式,你甚至可以像下边这样来嵌套,指明例外规则:

nav {
  border: 1px solid #ccc {
  left: 0px;
  right: 0px;
  }
}

编译之后

nav {
  border: 1px solid #ccc;
  border-left: 0px;
  border-right: 0px;
}

猜你喜欢

转载自www.cnblogs.com/heson/p/11263041.html