共通のスタイルを使いまわせる @mixin

メモ:  Category:front-end

@mixin とは、利用頻度の高いスタイルを定義しておき、必要に応じて定義したスタイルを使いまわせる(@include)機能です。また、引数が使えるためより柔軟な定義が可能となります。

@mixin の基本

@mixin は、再利用したいスタイルを @mixin hoge {} の形式で定義し、利用したい所で @include hoge として呼び出します。

@mixin _btn() {
  display: inline-block;
  cursor: pointer;
  line-height: 1;
  overflow: hidden;
  text-align: center;
  text-decoration: none;
  vertical-align: middle;
  white-space: nowrap;
}

.c-btn {
  @include _btn();
  background-color: #fff;
}

この SCSS をコンパイルすると次のように出力されます。

.c-btn {
  display: inline-block;
  cursor: pointer;
  line-height: 1;
  overflow: hidden;
  text-align: center;
  text-decoration: none;
  vertical-align: middle;
  white-space: nowrap;
  background-color: #fff; }

@mixin として定義したスタイルが、 .c-btn のスタイルに展開されて定義されたことが確認できます。

@mixin では引数が使える

@mixin では、「引数」を使うことができるため柔軟性のある部品(スタイル)を用意することができます。

引数を使う場合、 「@mixin hoge($arg){}」 の形式で丸括弧の中に引数指定して定義します。引数は、カンマで区切ることで複数指定することもできます。

@mixin _circle($size) {
  border-radius: 100%;
  height: $size;
  width: $size;
  overflow: hidden;
}

.c-circle {
  @include _circle(30px);
}

.c-circle--large {
  @include _circle(100px);
}

コンパイルを行うと引数に与えた値をもとに @mixin の内容が展開され出力されます。

.c-circle {
  border-radius: 100%;
  height: 30px;
  width: 30px;
  overflow: hidden; }

.c-circle--large {
  border-radius: 100%;
  height: 100px;
  width: 100px;
  overflow: hidden; }

引数にデフォルト値を設定する

@mixin では、引数を省力した場合のデフォルト値を「引数:デフォルト値」の形式で指定することができます。

@mixin _circle($size:50px) {
  border-radius: 100%;
  height: $size;
  width: $size;
  overflow: hidden;
}

.c-circle {
  @include _circle();
}

.c-circle--large {
  @include _circle(100px);
}

.c-circle の @include では、引数を指定していませんが、このままコンパイルを行うと次のようにデフォルト値が適用され CSS が出力されます。

.c-circle {
  border-radius: 100%;
  height: 50px;
  width: 50px;
  overflow: hidden; }

.c-circle--large {
  border-radius: 100%;
  height: 100px;
  width: 100px;
  overflow: hidden; }

Sass では 、「 & 」を使って親セレクタを参照する事ができるのですが、それらと組み合わせたりすることで @mixin はより便利に使うことが出います。

bluenote by BBB