LoginSignup
68
73

More than 5 years have passed since last update.

Rails + Compass でCSSの開発を高速化!

Posted at

巷で話題(?)のCompassをRailsに導入する方法です。
やることは簡単なんですが、GithubのCompass-Rails を参考にして導入したら、すこしハマったので備忘録として。
Railsのバージョンは3.2.13です。

初期設定

まずはGemfileへgemを追加。

Gemfile
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  gem 'compass-rails'

  gem 'uglifier', '>= 1.0.3'
end

bundle installを実施。
※私は本体のrubyへ直接gemを保存せず、Railsアプリ毎にローカルへinstallしています。

console
bundle install --path .bundle

Compassの初期設定を実行。
※Githubでは「rails」の項目がなく、Rails用ではない通常の初期設定が走るようになっていました。
※be は bundle exec のエイリアスを設定しているため、頭につけて実行しています。

console
be compass init rails

あとはstylesheetsのファイルをSassで書くだけ!

基本的な使い方

RailsのAsset Pipelineでは、CSSはSassを採用しているため、先ほどの初期設定で追加されたscreen.css.scssprint.css.scssie.css.scssが、そのまま利用することができます。
試しに'screen.css.scss'をみてください。

app/assets/stylesheets/screen.css.scss
/* Welcome to Compass.
 * In this file you should write your main styles. (or centralize your imports)
 * Import this file using the following HTML or equivalent:
 * <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
*/

@import "compass/reset";

すでにデフォルトでresetのモジュールが組み込まれています。
例えば以下のように設定すると、

app/assets/stylesheets/screen.css.scss
@import "compass/reset";
@import "compass";

.box {
    width: 100px;
    height: 100px;
    background:gray;
    @include border-radius();
}

Compassのモジュールを追加し(Resetはリセットの内容しか読み込まないため)、
@include で 希望のmix-inを読み込みます。

css
.box {
  width: 100px;
  height: 100px;
  background: gray;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  -o-border-radius: 10px;
  border-radius: 10px;
}

角丸のCSS(プレフィックス付き)として展開されます。
※IE対応のプリフィックスがつかなくなったようなので、注意が必要です。

利用できるmix-inはこちらにあります。
Compass / CSS3 のmix-in

CSS Spriteについて

ちまちまジェネレーターで作っていたのが悲しくなります。。
これは便利です!

  1. まずはimagesの中にCSS Spriteを適用したい画像を格納します。
    一枚の画像にまとめられるので、PNGで保存です。

  2. そして、Sassファイルで以下の2行を入力するだけ!

app/assets/stylesheets/screen.css.scss
@import "icons/*.png";
@include all-icons-sprites;
  1. あとは通常通り、1枚ごとの画像サイズにあわせてwidthとheightを設定し、classで画像を指定します。 実際のクラス名は'フォルダ名+画像名なので、例えばiconsフォルダでbag.pngファイルであれば、icons-bag.png`となります。

Compassは多機能かつSassと合わせてプログラミング的にCSSがかけるので、
使いこなすとさらに便利になりそうです。

ぜひ、便利なCompassライフを!

68
73
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
68
73