@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;}