001.使用变量及计算
1. 使用变量
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
编译后
body {
font: 100% Helvetica, sans-serif;
color: #333;
}
2. 变量名不区分中划线和下划线分隔
$link-color: blue;
a {
color: $link_color;
}
编译后
a {
color: blue;
}
3. 计算功能
body {
$var: 200px;
margin: (14px/2);
top: 50px + 100px;
right: $var * 10%;
color: hsl(0, 100%, 50%);
}
编译后
body {
margin: 7px;
top: 150px;
right: 20px;
color: #ff0000;
}
4. 键值对形式传参
body {
color: hsl($hue: 0, $saturation: 100%, $lightness: 50%);
}
编译后
body {
color: #ff0000;
}
5. 插值:#{}
您还可以通过 #{} 插值语法在选择器和属性名中使用Sass变量.
$name: foo;
$attr: border;
p.#{$name} {
#{$attr}-color: blue;
}
编译后
p.foo {
border-color: blue; }
也可以使用#{}将Sass转换为属性值。 在大多数情况下,这不比使用变量更好,但使用#{}意味着任何附近的操作将被视为纯CSS。
p {
$font-size: 12px;
$line-height: 30px;
font: #{$font-size}/#{$line-height};
}
编译后
p {
font: 12px/30px; }
6. 使用&判断是否存在父选择器
@mixin does-parent-exist {
@if & {
&:hover {
color: red;
}
} @else {
a {
color: red;
}
}
}
7. !default
如果分配给变量的值后面添加了!default标志 如果尚未赋值,那么会被赋予新的给定值。
$content: "First content";
$content: "Second content?" !default;
$new_content: "First time reference" !default;
#main {
content: $content;
new-content: $new_content;
}
编译后
#main {
content: "First content";
new-content: "First time reference"; }
通过!default赋值的时候,如果变量是null 值时,将视为未赋值
$content: null;
$content: "Non-null content" !default;
#main {
content: $content;
}
编译后
#main {
content: "Non-null content"; }