SASS—混合指令 (Mixin Directives)

混合指令(Mixin)用於定義可重複使用的樣式,避免了使用無語意的 class,比如 .float-left。混合指令可以包含所有的 CSS 規則,絕大部分 Sass 規則,甚至通過參數功能引入變量,輸出多樣化的樣式。

9.1. 定義混合指令 @mixin (Defining a Mixin: @mixin)

混合指令的用法是在 @mixin 後添加名稱與樣式,比如名爲 large-text 的混合通過下面的代碼定義:

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

——————————————————————————————————————————————————————

4.3. 屬性嵌套 (Nested Properties)

有些 CSS 屬性遵循相同的命名空間 (namespace),比如 font-family, font-size, font-weight 都以 font 作爲屬性的命名空間。爲了便於管理這樣的屬性,同時也爲了避免了重複輸入,Sass 允許將屬性嵌套在命名空間中,例如:

.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}

編譯爲

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; }

—————————————————————————————————————————————————————— 

9.2. 引用混合樣式 @include (Including a Mixin: @include)

使用 @include 指令引用混合樣式,格式是在其後添加混合名稱,以及需要的參數(可選):

.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

編譯爲

.page-title {
  font-family: Arial;
  font-size: 20px;
  font-weight: bold;
  color: #ff0000;
  padding: 4px;
  margin-top: 10px; }

混合樣式中也可以包含其他混合樣式,比如

@mixin compound {
  @include highlighted-background;
  @include header-text;
}
@mixin highlighted-background { background-color: #fc0; }
@mixin header-text { font-size: 20px; }

9.3. 參數 (Arguments) 

參數用於給混合指令中的樣式設定變量,並且賦值使用。在定義混合指令的時候,按照變量的格式,通過逗號分隔,將參數寫進圓括號裏。引用指令時,按照參數的順序,再將所賦的值對應寫進括號:

@mixin sexy-border($color, $width) {
  border: {
    color: $color;
    width: $width;
    style: dashed;
  }
}
p { @include sexy-border(blue, 1in); }

編譯爲

p {
  border-color: blue;
  border-width: 1in;
  border-style: dashed; }

就瞭解這些吧,其他自己看文檔 https://www.sass.hk/docs/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章