1. 程式人生 > >[Sass]混合宏

[Sass]混合宏

absolute idt -1 有一個 shadow nbsp center osi eight

[Sass]混合宏-聲明混合宏

在 Sass 中,使用“@mixin”來聲明一個混合宏。

[Sass]混合宏-調用混合宏

“@include”來調用聲明好的混合宏

@mixin 類似函數聲明,@include 類似函數調用

不帶參數混合宏

如:聲明:

@mixin border-radius{

    -webkit-border-radius
: 5px; border-radius: 5px; }

在一個按鈕中調用:

button {

    @include border-radius;}

帶參數混合宏

Sass 的混合宏有一個強大的功能,可以傳參,那麽在 Sass 中傳參主要有以下幾種情形:

A) 傳一個不帶值的參數

在混合宏中,可以傳一個不帶任何值的參數,比如:

@mixin border-radius($radius){

  -webkit-border-radius: $radius;

  border-radius: $radius;

}

調用的時候給這個混合宏傳一個參數值:

.box 
{ @include border-radius(3px); }

編譯出來的 CSS:

.box {

  -webkit-border-radius: 3px;

  border-radius: 3px;

}

B) 傳一個帶值的參數

給混合宏的參數傳一個默認值,例如:

@mixin border-radius($radius:3px){

  -webkit-border-radius: $radius;

  border-radius: $radius;

}

調用:

.btn {

  @include border-radius;

}

編譯出來的 CSS:

.btn {

  -webkit-border-radius: 3px;

  border-radius: 3px;

}

但有的時候,頁面中有些元素的圓角值不一樣,那麽可以隨機給混合宏傳值,如:

.box {

  @include border-radius(50%);

}

編譯出來的 CSS:

.box {

  -webkit-border-radius: 50%;

  border-radius: 50%;

}

C) 傳多個參數

@mixin center($width,$height){

  width: $width;

  height: $height;

  position: absolute;

  top: 50%;

  left: 50%;

  margin-top: -($height) / 2;

  margin-left: -($width) / 2;

}

調用:

.box-center {

  @include center(500px,300px);

}

編譯出來 CSS:

.box-center {

  width: 500px;

  height: 300px;

  position: absolute;

  top: 50%;

  left: 50%;

  margin-top: -150px;

  margin-left: -250px;

}

有一個特別的參數“”。當混合宏傳的參數過多之時,可以使用參數來替代,如:

@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: $shadow;

    box-shadow: $shadow;

  }

}

在實際調用中:

.box {

  @include box-shadow(0 0 1px rgba(#000,.5),0 0 2px rgba(#000,.2));

}

color:rgba(#b3b3b3, .25)sass中能這樣寫,css中不能

編譯出來的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);

}

復雜的混合宏:

上面是一個簡單的定義混合宏的方法,當然, Sass 中的混合宏還提供更為復雜的,可以在大括號裏面寫上帶有邏輯關系,如:

@mixin box-shadow($shadow...) {

  @if length($shadow) >= 1 {

    @include prefixer(box-shadow, $shadow);

  } @else{

    $shadow:0 0 4px rgba(0,0,0,.3);

    @include prefixer(box-shadow, $shadow);

  }

}

這個 box-shadow 的混合宏,帶有多個參數,這個時候可以使用“ … ”來替代

[Sass]混合宏