Scss中的嵌套规则

目录css

1. Sass 容许将一套 CSS 样式嵌套进另外一套样式中,内层的样式将它外层的选择器做为父选择器html

2.  父选择器 &app

3. 属性嵌套spa


1. Sass 容许将一套 CSS 样式嵌套进另外一套样式中,内层的样式将它外层的选择器做为父选择器

#app {  
  h1 {
    text-align: center;
  }
}

编译结果firefox

#app h1 { text-align: center; }

避免了重复输入父选择器,并且令复杂的 CSS 结构更易于管理code

2.  父选择器 &

在上一个例子中若是父子嵌套,可是我想操做 #app:hover  此时能够用 & 表明嵌套规则外层的父选择器。orm

a {
  font-weight: bold;
  text-decoration: none;
  &:hover { text-decoration: underline; }
  body.firefox & { font-weight: normal; }
}

编译为htm

a {
  font-weight: bold;
  text-decoration: none; 
}
a:hover {
  text-decoration: underline;
}
body.firefox a {
  font-weight: normal; 
}

 编译后的 CSS 文件中 & 将被替换成嵌套外层的父选择器,若是含有多层嵌套,最外层的父选择器会一层一层向下传递io

&所在的位置只表明了他的父亲,也就是说在每一层,指向是都是他所在的父元素。编译

#main {
  color: black;
  a {
    font-weight: bold;
    &:hover { color: red; }
  }
}

编译为

#main {
  color: black; 
}
#main a {
   font-weight: bold; 
}
#main a:hover {
  color: red; 
}

3. 属性嵌套

有些 CSS 属性遵循相同的命名空间 (namespace),好比 font-family, font-size, font-weight 都以 font 做为属性的命名空间。为了便于管理这样的属性,同时也为了不了重复输入,Sass 容许将属性嵌套在命名空间中,例如:

.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}

编译为

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; 
}

命名空间也能够包含本身的属性值,例如:

.funky {
  font: 20px/24px {
    family: fantasy;
    weight: bold;
  }
}

编译为

.funky {
  font: 20px/24px;
  font-family: fantasy;
  font-weight: bold; 
}