&符的使用
Sass中&符号包含对当前选择器以及任何父项的引用。
.A {
// & = '.A'
.B {
// & = '.A .B'
.C {
// & = '.A .B .C'
}
}
}
如果您喜欢使用BEM(块(Block),元素(Element),修饰符(Modifier))命名规范,&符会帮您快速创建新的选择器。
.MyComponent {
line-height:2.2;
&-title{
font-size:16px;
}
&-content{
color:#f00;
}
}
//编译为
.MyComponent {line-height:2.2;}
.MyComponent-title {font-size:16px;}
.MyComponent-content {color:#f00;}
有时候class类名还需要修饰符,使用&符号模式可以更轻松地创建修饰符。
<div class="MyComponent MyComponent--current"></div>
.MyComponent {
&--current {}
}
// 编译为
.MyComponent {}
.MyComponent--current {}
当然您也可以创建一个局部的修饰符。
<div class="MyComponent current"></div>
.MyComponent {
&.current {}
}
// 编译为
.MyComponent {}
.MyComponent.current {}
Sass变量和作用域
在了解Sass变量之前,需要先了解一下它们的作用域。Sass变量如果在选择器外部声明,则该变量在声明后对文档中的每个选择器都可用。
$fontSize: 1.4rem;
.a { font-size: $fontSize; }
.b { font-size: $fontSize; }
选择器内部声明的变量仅限于该选择器及其子项。
$fontSize: 1.4rem;
.MyComponent {
$fontWeight: 600;
font-size: $fontSize;
&-title {
font-weight: $fontWeight; // Works!
}
}
.MyComponent2 {
font-size: $fontSize;
&-title {
font-weight: $fontWeight; // produces an "undefined variable" error
}
}
Sass变量不但可以存储字体名称,整数,颜色等。它还可以存储选择器。
// Sass string interpolation syntax is #{VARIABLE}
$block: ".MyComponent";
#{$block} {
&-title {
#{$block}--xmasTheme & {
}
}
}
// Compiles to
.MyComponent {}
.MyComponent-title {}
.MyComponent--xmasTheme .MyComponent-title {}
上例中的Sass变量是全局作用域的。我们可以通过在组件中声明创建$block变量来解决这一问题,该变量将作用域限定到该组件。
.MyComponent {
$block: '.MyComponent';
&-title {
#{$block}--xmasTheme & {
}
}
&-content {
#{$block}--xmasTheme & {
}
}
}
// Compiles to
.MyComponent {}
.MyComponent-title {}
.MyComponent--xmasTheme .MyComponent-title {}
.MyComponent-content {}
.MyComponent--xmasTheme .MyComponent-content {}
#{$block}--xmasTheme好像是重复的。让我们把它存储在一个变量中!
.MyComponent {
$block: '.MyComponent';
$xmasTheme: '.MyComponent--xmasTheme';
&-title {
#{$xmasTheme} & {
}
}
}
其实Sass变量量还可以存储&符号的值!
.MyComponent {
$xmasTheme: #{&}--xmasTheme;
&-title {
#{$xmasTheme} & {
font-size:18px;
}
}
}
// Compiles to
.MyComponent--xmasTheme .MyComponent-title {
font-size: 18px; }