css中雪碧图(sprite)的使用及制作方法

雪碧图(sprite)是减少请求次数的有效手段,其原理是把多张图片进行合成,使用时通过css进行定位。

1.先看一下雪碧图

没有使用雪碧图时图标是这样一个个的单独文件:

合成雪碧图后是这样拼在一起的一张图:

 2.雪碧图的使用

首先确定要使用的图标的位置和大小(可以通过ps测量),

如下的雪碧图大小统一,排列规则

 

它们的大小均为30px*30px,第一个图标位置为0 0,第二个的位置为30px 0,依次...

样式可以这样写:

 1 .box1 li:nth-child(1) {
 2   width: 30px;
 3   height: 30px;
 4   background: url(./images/map-icon.png) no-repeat 0 0; /* 第一个图标*/
 5 }
 6 
 7 .box1 li:nth-child(2) {
 8   width: 30px;
 9   height: 30px;
10   background: url(./images/map-icon.png) no-repeat -30px 0; /* 第二个图标*/
11 }
12 
13 .box1 li:nth-child(3) {
14   width: 30px;
15   height: 30px;
16   background: url(./images/map-icon.png) no-repeat -60px 0; /* 第三个图标*/
17 }

页面上效果:

 

 

 排列不规则的雪碧图测量计算就不太方便了,推荐一个在线雪碧图样式工具http://tools.jb51.net/code/css_sprite

 

 3.合成雪碧图

如果没有美工MM给我们做图,自己找来的很多零碎图标(.png)可以使用CssSprite工具进行合成。

CssSprite.exe使用较为简单,选择图片后,可以竖排或横排,也能手动调整位置;设置css中路径名及保存名称,生成雪碧图即可,可以同时生成对应的css代码。

 

 工具源码地址:

https://github.com/iwangx/sprite

编译后的exe工具:

https://github.com/shiyuan598/htmlcss/raw/master/sprite/tools/CssSprite.exe

 

另外也有在线工具可用:

https://www.toptal.com/developers/css/sprite-generator

 

posted on 2020-03-18 23:06  橘生淮南_  阅读(1781)  评论(0编辑  收藏  举报