SCSS常用基础功能整理

 Sass 是一门高于 CSS 的元语言,它能用来清晰地、结构化地描述文件样式,有着比普通 CSS 更加强大的功能。
 Sass 能够提供更简洁、更优雅的语法,同时提供多种功能来创建可维护和管理的样式表。
其中Scss就是演化于Sass,Sass诞生于Ruby社区,只不过Sass写法更加的精简,Sass是有严格的缩进规范并且没有‘{}’和‘;’。而Scss则和css的规范是一致的。

mixin

 可以设置的通用样式,避免繁琐的重复代码,让css看起来更具条理性
 关键字@mixin @include

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//定义一个debug样式
@mixin dbug {
border: 1px solid red;
}
#container {
//使用关键字@include使用该样式
@include dbug;
.box1 {
color: red;
}
.box2 {
color: blue;
}
}

 当然mixin里面也和js的函数一样,可以接受参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@mixin dbug($color) {
//接受形参$color
border: 1px solid $color;
}
#container {
$R: #eee;//定义一个color值
@include dbug($R);
>.box1 {
color: red;
}
>.box2 {
color: blue;
}
}


%placeholder

 placeholder的用法和mixin的用法差不多一样,只是不能接受参数,使用时前面修饰符是@extend
 关键字% @extend ,那么用%placeholder的方式上面可以写成

1
2
3
4
5
6
7
8
9
10
11
12
13
//不能接受参数
%dbug{
border: 1px solid red;
}
#container {
@extend %dbug;
>.box1 {
color: red;
}
>.box2 {
color: blue;
}
}


&以及冒号:的运用

 &代表着当前选择器,:冒号相当于一个连接符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.userCard{
width: 100px;
//多类选择器
&.active{
background: yellow;
}
//详当于是 .userCard-name 的写法
&-name{
color: black;
// font-size font-weight
font:{
size: 28px;
weight: bold;
}
}
}


除法运算

 以下三种情况 / (斜杠)将被视为除法运算符号:

 1.如果值,或值的一部分,是变量或者函数的返回值
 2.如果值被圆括号包裹
 3.如果值是算数表达式的一部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
p {
font: 10px/8px; // 直接使用除法,不会触发运算
$width: 1000px;
width: $width/2; // 使用变量,触发运算
width: round(1.5)/2; // 使用一个函数,触发运算
height: (500px/2); // 使用括号,触发运算
margin-left: 5px + 8px/2px; // 使用加号,触发运算
}

编译为

p {
font: 10px/8px; //直接使用 / (斜杠),并未被编译
width: 500px;
height: 250px;
margin-left: 9px;
}


媒体查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//手机宽度
@mixin phone {
@media (max-width: 500px) {
@content;
}
}
//ipad宽度
@mixin ipad {
@media (min-width: 501px) and (max-width: 1024px) {
@content;
}
}
//pc宽度
@mixin pc {
@media (min-width: 1025px) {
@content;
}
}

//使用
#container{
@include phone {
background: red;
}
@include ipad{
background: blue;
}
@include pc{
background: green;
}
}


@function的使用

这个和js的写法都差不多,可以传入一个参数,并返回处理后的数据

1
2
3
4
5
6
7
8
@function px($value){
@return $value/2 + px;
}
#container{
width: px(200);
height: px(200);
background:#000;
}