CSS图像精灵

时间:2016-02-28 11:36:52

标签: css

我在我的网站上使用了4个单独的图像,现在,如果我使用图像精灵来显示这4个图像,它会减少http请求,如果是这样我就会想知道。

考虑以下示例1 :(此处发送2个http请求)

<!DOCTYPE html>
  <html>
  <head>
  <style>
 #home {
width: 46px;
height: 44px;
background: url(sevenwonders.gif) 0 0;//first http request
}

#next {
width: 43px;
height: 44px;
background: url(sevenwonders.gif) -91px 0; //second http request
}
</style>
</head>
<body>

<img id="home" src="something.gif"> 
<img id="next" src="something.gif">

</body>
</html>

考虑以下示例2(发送2个http请求)

 <!DOCTYPE html>
 <html>
 <head>
 </head>
 <body>

 <img id="home" src="tajmahal.gif">//first http request
 <img id="next" src="pisatower.gif">//second http request

 </body>
 </html>

非常感谢你宝贵的时间。

2 个答案:

答案 0 :(得分:1)

按照您的代码并使用示例图像进行说明,以下证明每个图像只会执行一次HTTP请求,无论是否重复。

请考虑以下事项:

<!DOCTYPE html>
  <html>
  <head>
  <style>
 #home {
width: 46px;
height: 44px;
background: url(http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image2.jpg) 0 0;//first http request
}

#next {
width: 43px;
height: 44px;
background: url(http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image2.jpg) -91px 0; //second http request
}
</style>
</head>
<body>

<img id="home" src="https://upload.wikimedia.org/wikipedia/commons/c/c3/Aurora_as_seen_by_IMAGE.PNG"> 
<img id="next" src="http://www.online-image-editor.com//styles/2014/images/example_image.png">

</body>
</html>

这只返回3个请求:正文中每个图像1个,CSS背景图像1个,使用两次。

Network tab on Chrome

但是,存在代码中滥用标记和CSS的问题。 您不应将image-background属性设置为img标记,该标记本身就是图像。

选择一种方法并坚持下去:使用身体中的图像(这将产生多个图像,因此需要多个请求)或使用具有指定div属性的background-image等中性元素,使用background-position来偏移精灵图像。

答案 1 :(得分:0)

首先,我想知道你为什么选择使用<img>标签并附上背景图片? 其次,每个图像src都是一个http请求(在css和html标签中),所以当你选择将图像显示为背景图像时,使用精灵肯定是个好主意。
您可以考虑将1px xpp透明gif加载到img标记的src以最小化http加载。 (你可以将它拉伸到所需的宽度和高度)

希望它有所帮助。

相关问题