转载http://www.shejidaren.com/css-sprites-optimize-retina-2x-image.html
Retina Display的出现有好有坏吧,坏处就是我们设计师要多做一份@2x版本的图像,如果不做的话在Retina显屏下会模糊。既然要做2份了,哪么我们可以利用CSS精灵(css sprites)来优化一下,CSS 精灵我想很多已经使用这项技术,具体制作过程网上有很多,本文主要讲如何用CSS精灵来优化Retina显示屏下的网站图像。
准备好图像
左边是普通图像,右边是Retina的图像(@2x)。
HTML代码:
1
2
3
4
|
<
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
>
|
使用独立图片写法
location.png
success.png
delete.png
favorite.png
location@2x.png
success@2x.png
delete@2x.png
favorite@2x.png
CSS代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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@
2
x.png);
background-
size
:
16px
14px
;
}
span.success {
background-image
:
url
(success@
2
x.png);
background-
size
:
13px
14px
;
}
a.delete {
background
:
url
(delete@
2
x.png)
no-repeat
0
-100px
;
}
.content a.fav-link {
background-image
:
url
(favorite@
2
x.png);
background-
size
:
11px
13px
;
}
}
|
使用CSS精灵写法
sprite.png
sprite@2x.png
CSS代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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@
2
x.png);
/* Translate the @2x sprite's dimensions back to 1x */
background-
size
:
200px
200px
;
}
}
|
判断为Retina显示屏的JS
我们可以能过
window.devicePixelRatio
来判断是否为Retina显示屏。
JavaScript
1
2
3
|
if
(window.devicePixelRatio == 2){
//for Retina Display
}
|