Sass混合宏实例介绍

在Sass中,我们可以使用“混合宏(mixin)”来处理经常被多个地方使用的相同的CSS代码块。混合宏,跟JavaScript中的函数很相似,我们可以称之为“Sass中的函数”。

 

一、混合宏的定义和调用

在Sass中,我们使用“@mixin”来定义一个混合宏,然后使用“@include”来调用一个混合宏。

语法:

//定义一个混合宏
@mixin 混合宏名
{
    样式属性1:取值1;
    样式属性2:取值2;
    ……
}
//调用一个混合宏
选择器
{
    @include 混合宏名;
}

说明:

Sass中的混合宏跟C语言的宏是非常相似的。所谓的“宏”,指的是可重用的代码块。

@mixin用来定义一个混合宏,@include用来调用一个混合宏。此外,@mixin跟CSS3中的@font-face和@media语法是一样的。

举例:

@mixin radius
{
    border-radius:5px;
    -webkit-border-radius:5px;
    -moz-border-radius:5px;
}
#header
{
    color:red;
    @include radius;
}
#footer
{
    color:green;
    @include radius;
}

编译出来的CSS代码如下:

#header
{
    color: red;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}
#footer
{
    color: green;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

 

二、混合宏的参数

在Sass中,我们不仅可以定义“不带参数的混合宏”,也可以定义“带参数的混合宏”。其中,混合宏的参数可以是1个,也可以是N个。

举例:带一个参数的混合宏

@mixin radius($radius)
{
    border-radius:$radius;
    -webkit-border-radius:$radius;
    -moz-border-radius:$radius;
}
#header
{
    color:red;
    @include radius(3px);
}
#footer
{
    color:green;
    @include radius(5px);
}

编译出来的CSS代码如下:

#header
{
    color: red;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
}
#footer
{
    color: green;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

举例:带多个参数的混合宏

@mixin center($width,$height)
{
    width: $width;
    height: $height;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -($height) / 2;
    margin-left: -($width) / 2;
}
div
{
    @include center(100px,80px);
}

编译出来的CSS代码如下:

div 
{
    width: 100px;
    height: 80px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -40px;
    margin-left: -50px;
}

分析:

这个混合宏里面的CSS代码是一个功能代码块,是用来同时实现元素的水平居中和垂直居中的。在实际开发中,对于这些功能代码块,我们都是配合混合宏(mixin)来使用,非常的简单快速。现在大家体会到Sass比纯CSS强大的地方了吧。

在Sass中,我们还可以为混合宏传递的参数定义默认值。混合宏参数的默认值,跟变量的默认值是非常相似的,小伙伴们记得对比一下,这样更能加深理解和记忆。

举例:参数带默认值

@mixin radius($radius:3px)
{
    border-radius:$radius;
    -webkit-border-radius:$radius;
    -moz-border-radius:$radius;
}
#header
{
    color:red;
    @include radius;
}
#footer
{
    color:green;
    @include radius(5px);
}

编译出来的CSS代码如下:

#header
{
    color: red;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
}
#footer
{
    color: green;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

分析:

在这个例子中,我们给“混合宏radius”传了一个参数“$radius”,并且给这个参数定义了一个默认值“3px”。如果我们页面有很多地方的圆角都是“3px”的话,那么这种默认值的方式就会非常好用。因为在调用的时候,我们只需要调用默认的“混合宏radius”就可以了。