9:sass中宏的使用

sass中Minxin的使用

Mixin有点像C语言的宏(macro),是可以重用的代码块。

sass

使用@minxin,定义一个代码块

@mixin left{
float: left;
margin-left: 10px;
}

使用@include命令,调用这个mixin。

.box{
@include left;
}
css:

.box {
float: left;
margin-left: 10px; }

mixin的核心是可以指定参数和缺省值

传入一个参数,可以指定默认值

sass

@mixin left($left:10px){
float: left;
margin-left: $left;
}
.box{
@include left;
}
css

.box {
float: left;
margin-left: 10px; }

传入一个参数

sass

@mixin left($left:10px){
float: left;
margin-left: $left;
}
.box{
@include left(20px);
}
css

.box {
float: left;
margin-left: 20px; }

传入多个参数

sass

@mixin rounded($first,$second,$radius:10px){
border-#{$first}-#{$second}-radius:$radius;
-webkit-border-#{$first}-#{$second}-radius:$radius;
-moz-border-#{$first}-#{$second}-radius:$radius;
}
.box{
@include rounded(top,left);
}
.nav{
@include rounded(bottom,left,20px);
}

css:

.box {
border-top-left-radius: 10px;
-webkit-border-top-left-radius: 10px;
-moz-border-top-left-radius: 10px; }

.nav {
border-bottom-left-radius: 20px;
-webkit-border-bottom-left-radius: 20px;
-moz-border-bottom-left-radius: 20px; }

条件判断宏

sass

@mixin box-shadow($shadows...){
@if(length($shadows) > 1){
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
@else {
$shadows:0 0 2px rgba(#000,.25);
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
}
.box{
@include box-shadow(0 0 1px rgba(#000,.5),0 0 2px rgba(#000,.2));
}
.nav{
@include box-shadow(0 0 1px rgba(#000,.5));
}

css:

.box {
-webkit-box-shadow: 0 0 1px rgba(0, 0, 0, 0.5), 0 0 2px rgba(0, 0, 0, 0.2);
box-shadow: 0 0 1px rgba(0, 0, 0, 0.5), 0 0 2px rgba(0, 0, 0, 0.2); }

.nav {
-webkit-box-shadow: 0 0 2px rgba(0, 0, 0, 0.25);
box-shadow: 0 0 2px rgba(0, 0, 0, 0.25); }

宏的不足:

生成的css文件中对重用模块不回复用,会形成冗余代码

sass:

@mixin left{
float: left;
margin-left: 10px;
}
.box{
@include left;
}
.nav{
@include left;
}

css:

.box {
float: left;
margin-left: 10px; }

.nav {
float: left;
margin-left: 10px; }

posted on 2016-04-26 20:15  借个火点烟  阅读(526)  评论(0)    收藏  举报