在 Sass 中,如果同一段 CSS 要在多處重複使用,可以把它定義成「混合宏(mixin)」。混合宏的概念與 JavaScript 的函式幾乎一致,因此也有人直接稱它為「Sass 中的函式」。
Sass 用 @mixin 定義混合宏,用 @include 呼叫它。
語法:
//定義一個混合宏
@mixin 混合宏名 {
樣式屬性1:取值1;
樣式屬性2:取值2;
……
}
//呼叫一個混合宏
選擇器 {
@include 混合宏名;
}
說明:
Sass 的混合宏與 C 語言的巨集概念相近——都是「可重複使用的程式碼塊」。另外,@mixin 的語法形式與 CSS3 的 @font-face、@media 屬於同一類 at-rule,讀起來不會陌生。
舉例:
@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;
}
混合宏可以沒有參數,也可以帶一個或多個參數,彈性比單純的變數高得多。
舉例:帶一個參數
@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;
}
分析:
這段混合宏封裝的是一個實用功能:讓元素同時水平與垂直置中。實務上這類「功能型程式碼塊」都適合用混合宏包裝,一行 @include 就能到處 reuse。這也讓你感受到 Sass 相比純 CSS 的強大之處。
此外,混合宏的參數還可以設定預設值,概念與變數預設值相同,兩邊對照記憶會更清楚。
舉例:參數帶預設值
@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;
}
分析:
如果全站的圓角多半是 3px,那麼把 3px 設為預設值就非常省事:多數地方直接 @include radius,遇到特例再傳參數覆寫。