1、定义变量
$ 定义变量
$side: left;
$font-sizes: (
xs: 10px,
sm: 12px,
md: 13px,
lg: 14px,
);
如果需要镶嵌在字符串中,则需要使用 #{}
border-#{$side}-radius: 5px;
2、允许使用计算方式
margin: (14px/2);
top: 50px + 100px;
right: $var * 10%;
// 颜色值运算
p {
color: #010203 + #040506;
//计算 01 + 04 = 05 02 + 05 = 07 03 + 06 = 09,然后编译为color: #050709
}
p {
color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75);
}
3、属性嵌套
注意要带冒号
font: {
size:18px;
color:red
}
也可以如下嵌套
nav {
border: 1px solid #ccc {
left: 0px;
right: 0px;
}
}
4、引用父元素&
a {
&:hover { color: #ffb3ff; } // &:hover 等价于 a:hover
}
&
作为选择器的第一个字符,其后可跟后缀生成复合的选择器
#main {
color: black;
&-sidebar { border: 1px solid; }
}
5、继承@extend
选择器可继承另一个选择器 @extend class2将具备class1+class2的属性
.class1 {
border: 1px solid #ddd;
}
.class2 {
@extend .class1;
font-size:120%;
}
6、重用代码@mixin
基本使用
使用@mixin
定义代码块
@mixin left {
float: left;
margin-left: 10px;
}
在使用时 需要调用@inclued
div {
@include left;
}
指定参数
@mixin left($value: 10px) {
float: left;
margin-right: $value;
}
使用的时候,根据需要加入参数:
div {
@include left(20px);
}
7、自定义函数
@function double($n) {
@return $n * 2;
}
#sidebar {
width: double(5px);
}
8、组合选择器>、+、~
子组合选择器>
选择article
元素的直接子元素section
article > section { border: 1px solid #ccc }
同层相邻组合选择器+
选择header
元素后紧跟的p
元素
header + p { font-size: 1.1em }
同层全体组合选择器~
选择所有跟在article
后的同层article
元素,不管它们之间隔了多少其他元素
article ~ article { border-top: 1px dashed #ccc }
9、Map函数
map-get( m a p , map, map,key)
根据 $key ,返回 $key 在 $map 中对应的 value 。如果 $key 不存在 $map中,返回 null 。
// colors
$colors: (
'primary': #db9e3f,
'info': #4b67af,
'danger': #791a15,
'blue-1': #1f3695,
'blue': #4394e4,
'white': #fff,
'white-1': #fcfcfc,
'white-2': #eceef0,
);
$border-color: map-get($colors, 'light-1');
// font size
$font-sizes: (
xs: 10px,
sm: 12px,
md: 13px,
lg: 14px,
);
font-size: map-get($font-sizes, 'md')
Sass 的 Map 函数还有 map-has-key(map, key),map-keys(map),map-merge(map1, map2),map-remove(map, keys…),map-values(map)。目前感觉map-get()
用得多一些。
10、控制指令
@each
@each
将变量 $var
作用于值列表中的每一个项目,然后输出结果。
@each $var in (left, center, right) {
.text-#{$var} {
text-align: $var;
}
}
编译得到三个class
.text-left{
text-align: left;
}
.text-center{
text-align: center;
}
.text-right{
text-align: right;
}
也可以同时利用$key
和$value
$colors: (
'primary': #db9e3f,
'info': #4b67af,
'danger': #791a15,
);
@each $colorKey, $color in $colors {
.text-#{$colorKey} {
color: $color;
}
}
@if
当 @if
的表达式返回值不是 false
或者 null
时,条件成立,输出 {}
内的代码
p {
@if 1 + 1 == 2 { border: 1px solid; }
@if null { border: 3px double; }
}
@if
声明后面可以跟多个 @else if
声明
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else {
color: black;
}
}
@for
这个指令包含两种格式:
@for $var from <start> through <end>
, 条件范围包含 <start>
与 <end>
或者 @for $var from <start> to <end>
,条件范围只包含 <start>
,不包含 <end>
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
编译为
.item-1 {
width: 2em; }
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }