[CSS]Retinaディスプレイを考慮したCSSスプライトの実装方法
Post on:2012年8月3日
sponsorsr
新しいiPad, iPhone4, MacBook Proなどに採用されているRetinaディスプレイを考慮したCSSスプライトの実装方法を紹介します。

Using CSS Sprites to optimize your website for Retina Displays
CSSスプライトとは複数のアイテムを一枚の画像に配置し、background-imageで表示する範囲を指定するテクニックです。複数の画像を一枚にまとめることで、トラフィックの軽減につながり、Googleをはじめ多くのサイトで利用されています。
Retinaディスプレイは通常のディスプレイの倍の解像度があり、最適化するためには倍の解像度をもった画像を使用する必要があります。
使用する画像をJavaScriptで記述するのも一つの手ですが、ここではスタイルシートのみで実装する方法を紹介します。
実装例は、4つのそれぞれ異なるクラスを定義した要素です。
HTML
HTMLはイメージしやすいようダミーです。
<span class="location">location</span> <span class="success">success</span> <span><a class="delete">delete</a></span> <span class="content"><a class="fav-link>fav-link</a></span>
CSSスプライトに使用する画像を用意します。
左は通常ディスプレイ用、右はRetinaディスプレイ用です。

CSS: 画像をアイテムごとに用意し、Retinaディスプレイ用にも用意する場合
- 用意する画像
-
- location.png
- success.png
- delete.png
- favorite.png
- location@2x.png
- success@2x.png
- delete@2x.png
- favorite@2x.png
span.location {
background: url(location.png) no-repeat 0 0;
}
span.success {
background: url(success.png) no-repeat 0 0;
}
a.delete {
background: url(delete.png) no-repeat 0 -100px;
}
.content a.fav-link {
background: url(favorite.png) no-repeat 0 0;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2) {
span.location {
background-image: url(location@2x.png);
background-size: 16px 14px;
}
span.success {
background-image: url(success@2x.png);
background-size: 13px 14px;
}
a.delete {
background: url(delete@2x.png) no-repeat 0 -100px;
}
.content a.fav-link {
background-image: url(favorite@2x.png);
background-size: 11px 13px;
}
}
CSS: Retina用のスプライト画像を用意する場合
- 用意する画像
-
- sprite.png
- sprite@2x.png
span.location {
background: url(sprite.png) no-repeat 0 0;
}
span.success {
background: url(sprite.png) no-repeat -100px 0;
}
a.delete {
background: url(sprite.png) no-repeat -100px -100px;
}
.content a.fav-link {
background: url(sprite.png) no-repeat 0 -100px;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2) {
span.location,
span.success,
a.delete,
.content a.fav-link {
/* Reference the @2x Sprite */
background-image: url(sprite@2x.png);
/* Translate the @2x sprite's dimensions back to 1x */
background-size: 200px 200px;
}
}
参考までに、JavaScriptでRetinaディスプレイを判別する際は下記のようになります。
JavaScript
if(window.devicePixelRatio == 2){
//for Retina Display
}
sponsors











