一、继承和占位符
二者都是经过
@extend
来引用。css
1.1 继承
一个已经存在的css样式类,能够被其余样式类继承。git
例如,实现如下css样式:github
.btn, .btn--primary, .btn--info { border: 1px solid blue; } .btn--primary { color: black; } .btn--info { color: gray; }
scss中能够这样写,显然,这种写法便于维护和阅读!web
.btn { border: 1px solid blue; } .btn--primary { color: black; @extend .btn; } .btn--info { color: gray; @extend .btn; }
1.2 占位符
顾名思义,若是不被
extend
引用,它是不会被编译,也就是:不会占用css文件大小。这是和继承最大区别。ruby
scss代码以下:函数
%btn { border: 1px solid blue; } // 没有被extend // 不会出如今css文件中 %test-btn { border: 1px solid black; } .btn--primary { color: black; @extend %btn; } .btn--info { color: gray; @extend %btn; }
编译后的css代码:测试
.btn--primary, .btn--info { border: 1px solid blue; } .btn--primary { color: black; } .btn--info { color: gray; }
2. 混合宏
scss中的函数,经过关键字
@mixin
声明,@include
引用。网站
2.1 参数设置和调用方式
无参调用 scss:url
@mixin btn { border-radius : 3px; } .box { color: white; @include btn; }
css:spa
.box { color: white; border-radius: 3px; }
参数调用 scss:
$radius:3px !default; @mixin btn($radius:5px) { // 默认是 5px border-radius : $radius; } .box { color: white; @include btn($radius); // 传入参数 }
css:
.box { color: white; border-radius: 3px; }
参数过多的状况
当参数二、3个时候,能够经过
@mixin size($width,$height)
这样来调用。当参数过多,使用...
符号。
scss:
$height: 15px !default; $width: 18px !default; @mixin size($list...) { @if length($list) == 0 { height: $height; width: $width; }@else if length($list) == 1 { height: $list; width: $list; }@else if length($list) == 2 { height: nth($list , 1); width: nth($list , 2); }@else { @debug "Too many parameters"; } } .btn--primary { @include size(); } .btn--big { @include size(20px , 25px); } .btn--square { @include size( 18px ); } .btn--test { @include size(1px,2px,3px,4px); // just a test. console output "Too many parameters" what we have defined. }
输出的css结果:
.btn--primary { height: 15px; width: 18px; } .btn--big { height: 20px; width: 25px; } .btn--square { height: 18px; width: 18px; }
2.2 好处和不足
混合宏最大的不足:会复用代码,形成css冗赘(能够尝试一下下方的测试代码)。 固然,符合宏能够传递参数这点很nice。
能够编译下方代码,观察下结果:
@mixin border-radius{ -webkit-border-radius: 3px; border-radius: 3px; } .box { @include border-radius; margin-bottom: 5px; } .btn { @include border-radius; }
3. 版本
- scss:3.5.6
- ruby:2.4.4p296
欢迎技术交流,引用请注明出处。 我的网站:godbmw.com Github:godbmw