LoginSignup
8
8

More than 5 years have passed since last update.

Compassのsprite-mapでハマった

Last updated at Posted at 2013-10-29

Compassでsprite-mapを使った時、
記述順を間違えると動いてくれないことがあるので、メモ。

これだとダメ。

$sprite-map: sprite-map("sprite/*.png");

%sprite-base{
    $sprite-path: sprite-path($sprite-map);
    $sprite-width: image-width("sprite/"#{$sprite-path}) / 2;
    $sprite-height: image-height("sprite/"#{$sprite-path}) / 2;

    background-image: sprite-url($sprite-map);
    background-size: $sprite-width $sprite-height;
    background-repeat: no-repeat;
}

コンパイルすると

Errno::ENOENT on line 28 of /Library/Ruby/Gems/1.8/gems/compass-0.12.2/lib/compass/sass_extensions/functions/image_size.rb: No such file or directory - ...

「ファイルがないよ!」と言われてしまう。

というのも、
sprite画像の使用を明示した時点でsprite画像が生成されるため、
画像情報を取得する関数は生成後に呼び出す必要がある。
この例ではimage-width/heightを、画像生成前に呼んでいるため、上記のようなエラーになってしまった。

以下のように、sprite-map変数を使った後であれば正しく動作する。

$sprite-map: sprite-map("sprite/*.png");

%sprite-base{
    background: $sprite-map;

    $sprite-path: sprite-path($sprite-map);

    $sprite-width: image-width("sprite/"#{$sprite-path}) / 2;
    $sprite-height: image-height("sprite/"#{$sprite-path}) / 2;

    background-size: $sprite-width $sprite-height;
}

もしくは、sprite-urlを一旦変数にキャッシュすることでも回避できる。

$sprite-map: sprite-map("sprite/*.png");
$sprite-url: sprite-url($sprite-map);

%sprite-base{
    $sprite-path: sprite-path($sprite-map);
    $sprite-width: image-width("sprite/"#{$sprite-path}) / 2;
    $sprite-height: image-height("sprite/"#{$sprite-path}) / 2;

    background-image: $sprite-url;
    background-size: $sprite-width $sprite-height;
    background-repeat: no-repeat;
}
8
8
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
8
8