ITコンサルの日常

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

Sass Tutorial - 8: @import

概要

原文

Stylesheets can get pretty big. CSS has an @import directive that allows you to break your styles up into multiple stylesheets, but each stylesheet takes a separate (slow) HTTP request. That's why Sass's @import directive pulls in the stylesheets directly. Not only that, but any variables or mixins defined in @imported files are available to the files that import them.


Sass has a naming convention for files that are meant to be imported (called “partials”): they begin with an underscore. Let's create a partial called _rounded.scss to hold our rounded mixin.


In order to support both .scss and .sass files, Sass allows files to be imported without specifying a file extension. That means we can just import "rounded", rather than "rounded.scss".

超意訳

スタイルシートはかなり大きくなることがあります。CSSには@import命令があり、複数のスタイルシートに分割することができますが、それぞれのスタイルシートは別々の(遅い)HTTPリクエストを必要とします。このことから、Sassの@import命令は直接スタイルシートを取り込んでいます。それだけでなく、@import命令によって取り込まれるファイルで定義されたどんな変数やmixinsも、取り込む側のファイルで利用可能です。


Sassは(“partials”と呼ばれる)取り込まれるファイルの命名規約を持っています。取り込まれるファイルは、アンダースコア始まりのファイル名を持ちます。前節Argumentsで作成したrounded mixinを保ちつつ、_rounded.scssというファイル名のpartial(取り込まれるファイル)を作ってみましょう。


.scssと.sassの両方をサポートするために、Sassはインポートするファイルの拡張子を指定しないことが可能です。そのため、import "rounded.scss"ではなく、import "rounded"とだけ書けば良いようになっています。

サンプル

scssファイル (_rounded.scss)
/* _rounded.scss */

@mixin rounded($side, $radius: 10px) {
  border-#{$side}-radius: $radius;
  -moz-border-radius-#{$side}: $radius;
  -webkit-border-#{$side}-radius: $radius;
}
scssファイル (style.scss)
/* style.scss */

@import "rounded";

#navbar li { @include rounded(top); }
#footer { @include rounded(top, 5px); }
#sidebar { @include rounded(left, 8px); }
cssファイル (sassコマンドにより自動生成)
/* style.scss */
/* _rounded.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; }



< Sass Tutorial - 7: Arguments | Sassの記事一覧 | Sassその他 - @extend >