CSS Sprites 图片整合技术

单介绍一下 CSS Sprites 的优点:
  • 当用户往U盘中拷200张图片,会等很久。但是如果弄成一个文件,再拷贝就会快很多。
  • CSS Sprites 的目的就是通过整合图片,减少对服务器的请求数量,从而加快页面加载速度。

实现方法

  1. 首先将小图片整合到一张大的图片上
  2. 然后根据具体图标在大图上的位置,给背景定位。
    background-position:-8px -95px;    

背景定位(background-position)

background-position 属性用来控制背景图片在元素中的位置。技巧是,实际上指定的是图片左上角相对于元素左上角的位置。

下面的例子中,设置了一个背景图片并且用 background-position 属性来控制它的位置,同时也设置了 background-repeat 为 no-repeat。计量单位是像素。第一个数字表示 x 轴(水平)位置,第二个是 y 轴(垂直) 位置。

/* 例 1: 默认值 */
background-position: 0 0; /* 元素的左上角 */

/* 例 2: 把图片向右移动 */
background-position: 75px 0;

/* 例 3: 把图片向左移动 */
background-position: -75px 0;

/* 例 4: 把图片向下移动 */
background-position: 0 100px;

background-position 属性可以用其它数值,关键词和百分比来指定,这比较有用,尤其是在元素尺寸不是用像素设置时。

关键词是不用解释的。x 轴上:

  • * left
  • * center
  • * right

y 轴上:

  • * top
  • * center
  • * bottom

顺序方面和使用像素值时的顺序几乎一样,首先是 x 轴,其次是 y 轴,像这样:

background-position: top right;

使用百分数时也类似。需要主要的是,使用百分数时,浏览器是以元素的百分比数值来设置图片的位置的。看例子就好理解了。假设设定如下:

background-position: 100% 50%;
This goes 100% of the way across the image (i.e. the very right-hand edge) and 100% of the way across the element (remember, the starting point is always the top-left corner), and the two line up there. It then goes 50% of the way down the image and 50% of the way down the element to line up there. The result is that the image is aligned to the right of the element and exactly half-way down it.

糖伴西红柿:这一段没想到合适的翻译,保留原文,意译。前端观察 版权所有,转载请保留链接。

update: 感谢 的指教,这段搞明白了。使用百分数定位时,其实是将背景图片的百分比指定的位置和元素的百分比位置对齐。也就是说,百分数定位是改变了背景图和元素的对齐 基点。不再像使用像素和关键词定位时,使用背景图和元素的左上角为对齐基点。例如上例的 background-position: 100% 50%; 就是将背景图片的 100%(right) 50%(center) 这个点,和元素的 100%(right) 50%(center) 这个点对齐。

这再一次说明了,我们一直认为已经掌握的简单的东西,其实还有我们有限的认知之外的知识。

最终的效果是笑脸图片被定位在元素的最右边,离元素顶部是元素的一半,效果和 background-position: right center; 一样。

原文地址:https://www.cnblogs.com/danghuijian/p/4400329.html