1.变量定义和使用
$designWidth: 750px; .className{ width:$designWidth; }
2.定义函数(无参数)
场景:对公共性的样式进行抽离成函数形式,在需要的地方进行调用即可,使用@mixin定义,使用@include调用。
//没有参数 @mixin ellipsis { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } //使用方式 .className{ max-width:100px; height:30px; @include ellipsis(); }
3.定义函数(带参数)
//带参数 浮动:默认值是left @mixin float($float:left) { float: $float; } //使用方式 .classNameLeft{ @include float(); } .classNameRight{ @include float(right); }
4.定义函数(带参数条件判断)
//带if条件判断 @mixin rectangle($width, $height, $i ,$borderColor ) { width: $width; height: $height; @if $i == 1 { border:1px solid $borderColor; background-color:red; } @else if $i == 2 { border:1px solid $borderColor; background-color:green; } @else if $i == 3 { border:1px solid $borderColor; background-color:#6ad474; } } //带参数 浮动:默认值是left .classNameRight{ @include rectangle(100px,50px,2,#f00); }
5.占位符%选择器的使用
sass中占位符选择器与常用的 id 与 class 选择器写法相似,只是 #
或 .
替换成了 %
。必须通过 @extend 指令调用 。
// ****************占位符选择器**************** %common-basic { // %编译后不会出现在css文件中 float: left; margin-top: 15px; width: 10px; height: 10px; } .basic-icon { @extend %common-basic; // @extend继承 background-color: red; } .basic-layout { @extend %common-basic; background-color: green; } // ****************普通选择器**************** .basic { // %编译后不会出现在css文件中 float: left; margin-top: 15px; width: 10px; height: 10px; } .basic-icon { @extend .basic; // 调用 @extend继承 background-color: red; }
通过@extend
和 @include
定义的样式,在浏览器上产生的效果是一样的,但是编译的结果却区别很大,如下:
//*************使用@extend************* %basic{ float: left; } .cls1{ @extend %basic; } .cls2{ @extend %basic; } //编译结果: .cls1,.cls2{ float: left; } //*************使用@include************* @mixin basic { float: left; } .cls1{ @include basic; } .cls2{ @include basic; } //编译结果: .cls1{ float: left; } .cls2{ float: left; }
可以看到, .cls1和
.cls2通过@mixin结合 @include使用时,继承部分重复了两次, 有冗余。但是用%
选择器配合@extend
就不会有这样的问题.。
6.循环的使用
1.for循环
在sass中的@for循环有两种方式:
①@for $i from <start> through <end> { … }
②@for $i from <start> to <end> { … }
其中$i表示变量,start表示开始值,end表示结束值;
through表示包括end这个数值;to表示不包括end这个数值;
$color: #42cb50, #8080ff, #d9001b, #817f7f, #787777, #ff5b6f, #117a1b, #ff7184, #8c8b8b; //@for $i from 1 through/to 9{} @for $i from 1 through length($color) { .box#{$i} { border: #{$i}px solid blue; } }
注:@for $i from 开始值 through 结束值 包含结束值 (SCSS 循环是从1开始的)
2.while循环
只要@while后面的条件是个表达式,为true就会执行,直到表达式值为false时停止循环;
$types: 4; $type-width: 20px; @while $types > 0 { .while—#{$types} { width: $type-width + $types; } $types: $types - 1; }
3.each in循环
就是去遍历一个列表,然后从列表中取出对用值;他的指令形式为:@each $var in <list>($var为变量值,list为sassscript表达式)
//例子1: $color: #42cb50, #8080ff, #d9001b, #817f7f, #787777, #ff5b6f, #117a1b, #ff7184, #8c8b8b; @each $c in $color { $i: index($color, $c); .color#{$i}0 { color: $c; item: $i; } } //例子2: @each $member in a, b, c, d { .#{$member} { background-image: url("/image/#{$member}.jpg"); } }
注:这里的循环体数据list在循环不能有重复的项,不然之后重复的项会出现失效的问题。
原创文章,作者:Ferrycoln,如若转载,请注明出处:https://ms200.cn/archives/1855