ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

Sass Tutorial - 7: Arguments

概要

原文

The real power of mixins comes when you pass them arguments. Arguments are declared as a parenthesized, comma-separated list of variables. Each of those variables is assigned a value each time the mixin is used.


Mixin arguments can also be given default values just like you'd declare them normally. Then the user of the mixin can choose not to pass that argument and it will be assigned the default value.

超意訳

Mixinsの真の力は、引数を渡すことによって発揮されます。引数は括弧で囲まれ、カンマで区切られた変数として定義されます。これらの変数のいずれも、mixinが使われるたびに、値が割り当てられます。


Mixinの引数には、通常引数を宣言するのと同様に、デフォルト値を与えることができます。mixinの利用者は引数を渡さないという選択もでき、そのときは、変数にはデフォルト値が割り当てられます。

サンプル

scssファイル
/* style.scss */

@mixin rounded($side, $radius: 10px) {
  border-#{$side}-radius: $radius;
  -moz-border-radius-#{$side}: $radius;
  -webkit-border-#{$side}-radius: $radius;
}

#navbar li { @include rounded(top); }
#footer { @include rounded(top, 5px); }
#sidebar { @include rounded(left, 8px); }
cssファイル (sassコマンドにより自動生成)
/* style.scss */
#navbar li {
  border-top-radius: 10px;
  -moz-border-radius-top: 10px;
  -webkit-border-top-radius: 10px; }

#footer {
  border-top-radius: 5px;
  -moz-border-radius-top: 5px;
  -webkit-border-top-radius: 5px; }

#sidebar {
  border-left-radius: 8px;
  -moz-border-radius-left: 8px;
  -webkit-border-left-radius: 8px; }

ちなみに

@mixin util($arg) {
  font-size: $arg;
}

.elem {
  @include util;
}

のように、デフォルト値のない引数があるにも関わらず、引数を渡さないとコンパイルエラーになります。

>sass test.scss test.css
Syntax error: Mixin util is missing parameter $arg.
on line 6 of test.scss, in `util'
from line 6 of test.scss
Use --trace for backtrace.



< Sass Tutorial - 6: Mixins | Sassの記事一覧 | Sass Tutorial - 8: @import >