首发日期:2018-05-01css
在之前,每一个图片资源都是独立的一张张图片,浏览器访问网站中的不一样网页时是重复获取这一张张图片的,这表明须要访问不少次资源。html
为了减小资源的访问次数,将多个经常使用的图片集合到一张图片中(网页的缓存机制是会略去本地已经有的资源,若是前一次获取到了这个资源,那么后面不会再访问了,直到缓存的资源失效了。【意思有点相似去游乐园,有些票能玩全部游戏,而有些票只能玩一个游戏,若是你拿着能玩全部游戏的票,那你就不用麻烦去一次次买票了】)。web
将多个经常使用的图片集合到一张图片中以后,把这个图设置成背景图片,而后利用background-position来显示图片的不一样部分。c#
下面是一张26字母表,咱们利用这张图来拼出一个GOOGLE浏览器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Document</title> <style> div{ display:inline-block; } div:first-child{ width:79px; height: 79px; background-image:url('abcd.jpg'); background-position:-396px 0; } div:nth-child(2){ width:82px; height: 82px; background-image:url('abcd.jpg'); background-position:-326px -98px; } div:nth-child(3){ width:82px; height: 82px; background-image:url('abcd.jpg'); background-position:-326px -98px; } div:nth-child(4){ width:79px; height: 79px; background-image:url('abcd.jpg'); background-position:-396px 0; } div:nth-child(5){ width:48px; height: 77px; background-image:url('abcd.jpg'); background-position:-81px -101px; } div:nth-child(6){ width:48px; height: 77px; background-image:url('abcd.jpg'); background-position:-286px 0; } </style> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </body> </html>
结果:svg
如上例所示,咱们能够把多张图片放到一张大图中,而后利用background-position就能够截取出咱们想要看到的内容.字体
在现实中不少的背景图片都使用了这种技术.网站
众所周知,单位字体的文件大小小于图片的大小,考虑精灵图处理的是一张张图片,有人就有了一个奇思妙想--把图片转换成字体(实际上字体原本就是那么设计下来的。)
转换成字体后,可使用特殊的代码来显示出指定的图片。
字体图标比精灵图有一个很是明显的好处,由于他是字体,因此它可以改变字体颜色,能改变字体大小(而且不会失真)。
例子:【下面仅演示使用,不演示如何制做字体图标】
我利用icomoon制做了一套字体图标,【icomoon有现成的图标选择】,并下载下来。下面是文件名。
style.css能提供一种使用字体图标的方式
而后使用:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Document</title> <style > /* 声明字体 这下面一堆文字在下载的文件夹中的css文件中*/ @font-face { font-family: 'icomoon'; src: url('fonts/icomoon.eot?ni3k5c'); src: url('fonts/icomoon.eot?ni3k5c#iefix') format('embedded-opentype'), url('fonts/icomoon.ttf?ni3k5c') format('truetype'), url('fonts/icomoon.woff?ni3k5c') format('woff'), url('fonts/icomoon.svg?ni3k5c#icomoon') format('svg'); font-weight: normal; font-style: normal; } /* 使用 */ [class^="icon-"], [class*=" icon-"] { /* use !important to prevent issues with browser extensions that change fonts */ font-family: 'icomoon' !important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-home:before { content: "\e900"; } .icon-image:before { content: "\e90d"; } .icon-music:before { content: "\e911"; } div{ font-family:'icomoon';/* 要与上面一致 */ } </style> </head> <body> <div class=".icon-imagee"></div> <!-- 第一种使用方式: 导入style.css文件,并使用指定图标的类选择器的属性做为对应的class属性值 --> <div></div> <!-- 第二种使用方式: 对标签进行字体声明,而后打开demo.html复制那个图标下来【左边一个代码,右边一个图标】 --> <!-- 第一种方法是使用::before来增长,咱们也可使用别的::before方式来添加 --> </body> </html>