11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sass/Compass:Sprite自動生成のRetina対応

Posted at

CompassのSprite自動生成は便利だがRetina対応はmixinを自作する必要がある。
ググるとRetina対応の記事が複数でてくるのだけど、background-sizeが決め打ちの記事ばかり。
spriteフォルダ内の個別画像によって生成されるSprite画像のサイズが変わるのだから、background-sizeも動的に設定したい。

ということで、
動的にbackground-sizeに対応+ちょっとしたパターン分けをいれたmixinを作った。

##コード

scss
$sprite: sprite-map("sprite/*.png");
%base-sprite {
	background: sprite-url($sprite);
	@include background-size(ceil(image-width(sprite-path($sprite)) / 2), auto);
  	background-repeat: no-repeat;
  	overflow: hidden;
}
@mixin sprite-background($name, $width: "false", $height: "false", $size: "true") {
	@extend %base-sprite;
	
	@if $size == "true" {
		@if $width == "false" {
			width: image-width(sprite-file($sprite, $name)) / 2;
		} @else {
			width: $width;
		}

		@if $height == "false" {
			height: image-height(sprite-file($sprite, $name)) / 2;
		} @else {
			height: $height;
		}
	}

	$ypos: round(nth(sprite-position($sprite, $name), 2) / 2);
	background-position: 0 $ypos;
}

##使用例

//▼SCSS

//1.画像サイズを出力する
. hoge {
	@include sprite-background("hoge");
}

//2.画像サイズを指定する
. fuga {
	@include sprite-background("fuga", 60px, 30px);
}

//3.画像サイズを省略する
. piyo {
	@include sprite-background("piyo", $size: "false");
}


//▼CSS
.hoge,.fuga, piyo {
  background: url('sprite-s7c7fcd639e.png');
  -webkit-background-size: 130px, auto;
  background-size: 130px, auto;
  background-repeat: no-repeat;
  overflow: hidden;
}

//1.画像サイズを出力する
.hoge {
  width: 29px;
  height: 17px;
  background-position: 0 -10px;
}

//2.画像サイズを指定する
.fuga{
  width: 60px;
  height: 30px;
  background-position: 0 -50px;
}

//3.画像サイズを省略する
. piyo {
  background-position: 0 -100px;
}

```

11
11
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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?