关于SASS的一些碎碎念

@extend 与 @mixin 的区别

1. @extend 命令不够灵活,不能传递参数。

@extend 只能传递代码片断,而@mixin 则可以传递参数。

如果只是这点区别的话,那可能有人就会想,我都用@mixin不就好了么。莫方,来看第二条。

2. 编译结果不一样。

@extend@mixin 都可以让我们利用样式片段,那它俩的区别主要是,使用 @extend 可以产生 DRY(Donot repeat youself)风格的代码。

例如:

%part{
  position: absolute;
  border-radius: 50%;
}

.box1{
  width: 30px;
  height: 30px;
  background: #ccc;
  @extend %part;
}
.box2{
  width: 10px;
  height: 10px;
  background: #000;
  @extend %part;
}

编译出来的结果是:

.box1, .box2 {
  position: absolute;
  border-radius: 50%;
}

.box1 {
  background: #ccc;
}

.box2 {
  background: #000;
}

我们发现样式片段没有重复。但是@mixin就不能产生DRY式的代码。

@mixin part{
  position: absolute;
  border-radius: 50%;
}

.box1{
  background: #ccc;
  @include part;
}
.box2{
  background: #000;
  @include part;
}

编译结果:

.box1 {
  background: #ccc;
  position: absolute;
  border-radius: 50%;
}

.box2 {
  background: #000;
  position: absolute;
  border-radius: 50%;
}

SASS随机函数 random()

1. 直接使用random()

直接使用则产生一个0-1的随机数,一般会有4-5个小数。

.box {
  opacity: random();    
}

输出:

.box {
  opacity: 0.59874; // 随机生成
}

2. 传参使用

random()接受一个大于等于1的整数。如果小于1或不为整数,则编译报错。

.box {
  font-weight: random(200);     // 随机生成1-200之间的整数
  font-weight: random(2.5);     // 报错:Expected $limit to be an integer but got 2.5 for `random'
}

使用随机数如果要跟单位,可以用+号连接它们,也可以用插值#{}包起来,例如:

.box {
  width: random(100) + px;
  height: #{random(100)}px;
}

但是random()不能连接%符号,如果需要生成百分比随机数,则需要用到下面的percentage()函数。

SASS百分比函数 percentage()

percentage() 函数可以把数字转化成百分比。例如:

.box {
  width: percentage(.6)
}

输出结果为:

.box {
  width: 60%;
}

如果随机数+百分比则可以这么写:

.box {
  width: percentage(random(100) / 100)
}

输出结果为:

.box {
  width: 60%; /* 值为随机生成 */
}

SASS for循环

两种方式

for 循环中有两种方式:

@for $i from through
@for $i from to

$i 表示变量 start 表示起始值 end 表示结束值
这两个的区别是关键字 through 表示包括 end 这个数,而 to 则不包括 end 这个数。
例如:

@for $i from 1 through 3{
  .box:nth-child(#{$i}){
    width: 100px;
  }
} 

编译结果为:

.box:nth-child(1) {
  width: 100px;
}

.box:nth-child(2) {
  width: 100px;
}

.box:nth-child(3) {
  width: 100px;
}
@for $i from 1 to 3{
  .box:nth-child(#{$i}){
    width: 100px;
  }
} 

编译结果为:

.box:nth-child(1) {
  width: 100px;
}

.box:nth-child(2) {
  width: 100px;
}

@for循环实例

雪碧图背景遍历

我们经常会合并相当大小的图标为一张雪碧图,一般这种雪碧图的背景定位是有规律遵循的,如:

@for $i from 0 through 2{
  .icon-#{$i+1}{
    background-position: #{$i*-30}px 0;
  }
}

编译结果为:

.icon-1 {
  background-position: 0px 0;
}
.icon-2 {
  background-position: -30px 0;
}
.icon-3 {
  background-position: -60px 0;
}

SASS 自定义函数 @function

Sass 支持自定义函数,并能在任何属性值或 Sass script 中使用:
例如:

@function pxToRem($px) {
  @return ($px / 100) * 1rem;
}
.text {
  font-size: pxToRem(240);
}

编译结果:

.text {
  font-size: 2.4rem;
}

你可能感兴趣的:(关于SASS的一些碎碎念)