若是你的整個網站中有幾處小樣式相似,好比顏色,字體等,在 Sass 能夠使用變量來統一處理,那麼這種選擇仍是不錯的。但當你的樣式變得愈來愈複雜,須要重複使用大段的樣式時,使用變量就沒法達到咱們目了。這個時候 Sass 中的混合宏就會變得很是有意義。css
在 Sass 中,使用「@mixin」來聲明一個混合宏。如:web
@mixin border-radius{ -webkit-border-radius: 5px; border-radius: 5px; }
其中 @mixin 是用來聲明混合宏的關鍵詞,有點相似 CSS 中的 @media、@font-face 同樣。border-radius 是混合宏的名稱。大括號裏面是複用的樣式代碼。字體
除了聲明一個不帶參數的混合宏以外,還能夠在定義混合宏時帶有參數,如:網站
@mixin border-radius($radius:5px){ -webkit-border-radius: $radius; border-radius: $radius; }
上面是一個簡單的定義混合宏的方法,固然, Sass 中的混合宏還提供更爲複雜的,你能夠在大括號裏面寫上帶有邏輯關係,幫助更好的作你想作的事情,如:code
@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 的混合宏,帶有多個參數,這個時候能夠使用「 … 」來替代。簡單的解釋一下,當 $shadow 的參數數量值大於或等於「 1 」時,表示有多個陰影值,反之調用默認的參數值「 0 0 4px rgba(0,0,0,.3) 」。it
在 Sass 中經過 @mixin 關鍵詞聲明瞭一個混合宏,那麼在實際調用中,其匹配了一個關鍵詞「@include」來調用聲明好的混合宏。例如在你的樣式中定義了一個圓角的混合宏「border-radius」:編譯
@mixin border-radius{ -webkit-border-radius: 3px; border-radius: 3px; }
在一個按鈕中要調用定義好的混合宏「border-radius」,能夠這樣使用:class
button { @include border-radius; }
這個時候編譯出來的 CSS:變量
button { -webkit-border-radius: 3px; border-radius: 3px; }