目录
1. Sass 允许将一套 CSS 样式嵌套进另一套样式中,内层的样式将它外层的选择器作为父选择器
1. Sass 允许将一套 CSS 样式嵌套进另一套样式中,内层的样式将它外层的选择器作为父选择器
#app {
h1 {
text-align: center;
}
}
编译结果
#app h1 { text-align: center; }
避免了重复输入父选择器,而且令复杂的 CSS 结构更易于管理
2. 父选择器 &
在上一个例子中如果父子嵌套,但是我想操作 #app 的:hover 此时可以用 &
代表嵌套规则外层的父选择器。
a {
font-weight: bold;
text-decoration: none;
&:hover { text-decoration: underline; }
body.firefox & { font-weight: normal; }
}
编译为
a {
font-weight: bold;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
body.firefox a {
font-weight: normal;
}
编译后的 CSS 文件中 &
将被替换成嵌套外层的父选择器,如果含有多层嵌套,最外层的父选择器会一层一层向下传递
&所在的位置只代表了他的父亲,也就是说在每一层,指向是都是他所在的父元素。
#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;
}