@content
# @content
向混合样式中导入内容 (Passing Content Blocks to a Mixin
)
在引用混合样式的时候,可以先将一段代码导入到混合指令中,然后再输出混合样式,额外导入的部分将出现在 @content
标志的地方:
@mixin apply-to-ie6-only {
* html {
@content;
}
}
@include apply-to-ie6-only {
#logo {
background-image: url(/logo.gif);
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
编译为
* html #logo {
background-image: url(/logo.gif);
}
1
2
3
2
3
为便于书写,@mixin
可以用 =
表示,而 @include
可以用 +
表示,所以上面的例子可以写成:
=apply-to-ie6-only
* html
@content
+apply-to-ie6-only
#logo
background-image: url(/logo.gif)
1
2
3
4
5
6
7
2
3
4
5
6
7
注意: 当 @content
在指令中出现过多次或者出现在循环中时,额外的代码将被导入到每一个地方。
传递给 mixin
的内容块在块定义的范围内计算,而不是在 mixin
的范围内计算。这意味着 mixin
的局部变量不能在传入的样式块中使用,变量将解析为全局值:
$color: white;
@mixin colors($color: blue) {
background-color: $color;
@content;
border-color: $color;
}
.colors {
@include colors { color: $color; }
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编译为
.colors {
background-color: blue;
color: white;
border-color: blue;
}
1
2
3
4
5
2
3
4
5
此外,这清楚地表明,在传递的块中使用的变量和 mixin
与块定义处的其他样式相关。例如:
#sidebar {
$sidebar-width: 300px;
width: $sidebar-width;
@include smartphone {
width: $sidebar-width / 3;
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7