LoginSignup
5
1

More than 3 years have passed since last update.

Sass(SCSS)で使用出来る@mixinについて

Last updated at Posted at 2019-09-14

始めに

作成した個人アプリをリファクタリングする際Sassの機能の一つ@mixinを使用したのでその使用方法について説明します。

@mixin(ミックスイン)とは?

定義したスタイルを別のスタイルに@includeを使用して何度も呼び出す事が可能になるというものです。
よく使うスタイルを@mixinで定義しておけばどこからでも@includeを使用すれば呼び出せるので、コードが見易くなり、メンテナンスもしやすくなります。

記述方法

先ずは基本的な使用方法から@mixinの後にクラス名を定義して使用します。
その後使用したいファイルに@includeを使用して定義します。

mixin.scss
@mixin white {
  color: white;
  font-size: 2rem;
}
test.scss
.test{
  @include white;
  float: left;
}


実際の中身
.test {
  color: white;
  font-size: 2rem;
  float: left;
}

後はパーシャルファイルを読み込むのを忘れないよう@importをファイル内に記述します。

application.scss
  @import "modules/mixin";
  @import "test";

引数を使用した方法

引数を使用した方法の場合は$引数名を()内に定義して使用します。

mixin.scss
@mixin centerwhite($size) {
  color: white;
  text-align: center;
  font-size: $size;
}

この様に定義する事で今回の場合はサイズ指定をする事が出来るようになります。
使用方法はクラス名の後の()の中に指定します。

test.scss
.test {
  @include centerwhite(2rem);
  float: left;
}

実際の中身
.test {
  color: white;
  text-align: center;
  font-size: 2rem;
  float: left;
}

2つ以上の引数の場合

()内に複数$引数名を使用する事で複数指定する事も可能になります。

mixin.scss
@mixin colorstyle($color,$size) {
  color: $color;
  font-size: $size;
}
test.scss
.test {
  @include colorstyle(white,2rem);
  float: left;
}

実際の中身
.test {
  color: white;
  font-size: 2rem;
  float: left;
}

この様に複数指定すれば、色やサイズなどの指定が容易に出来、メンテナンスもしやすくなる為、便利だと思います。

最後に

以上基本的な@mixinの使用方法でした。この他にも色々応用的な使用方法もありますので、今後使いこなせる様になれたらと思います。
以下、参考にさせて頂いた資料です。
https://www.webcreatorbox.com/tech/sass-mixin

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1