因为我也不是CSS高手,所以本文的目的是写清楚如何弄明白CSS中分割图片的技巧,说到分割其实并不是真正意义上的剪裁图片,只是已经流行多年了的一种CSS best practise,用一个拼接起来的大的图片资源替代加载多个小图片的一种方法,优点是节约页面的加载速度,不会出现有的图片能显示有的还在加载的情况,这个效果或者性能用firebug可以测试出来。

当然用这个技巧也要选对地方用才行,要是经常需要改动的图像用这个技术还是有点折腾的。

核心的属性是这个:background-position 参数值从w3schools找出来的

Property Values

Value Description
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
If you only specify one keyword, the second value will be “center”. Default value is: 0% 0%
x% y% The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%.
xpos ypos The first value is the horizontal position and the second value is the vertical. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions
inherit Specifies that the setting of the background-position property should be inherited from the parent element

这里有篇不错的文章描述的是下面这个例子,将原图竖着的1234显示成横着的4个盒子
CSS: Using Percentages in Background-Image


.box1
.box2
.box3
.box4

下面这个例子也是常用到的:
鼠标移到按钮上,用稍微亮一点点的图片显示的悬停效果。
用到的green.png原图: green.png
按钮的代码:

<a class="green" href="#">Green<span> </span></a>

按钮的CSS:

a {
	/* The section titles */
	display:block;
	font-size:21px;
	height:34px;
	overflow:hidden;
	padding:10px 20px 0;
	position:relative;
	width:200px;
}
a {
	text-decoration: none;
}
a:hover{
	/* Removing the inherited underline from the titles */
	text-decoration:none;
}
a span{
	/* This span acts as the right part of the section's background */
	height:44px;
	position:absolute;
	right:0;
	top:0;
	width:4px;
	display:block;
}
a.green{background:url(img/green.png) repeat-x top left; color:#436800;}
a.green span{ background:url(img/green.png) repeat-x top right;}
/* The hover effects */
a:hover{ background-position:bottom left;}

最重要的一行,鼠标移上去的时候设置图像的位置为bottom left,而下半部分的图像比上半部分亮一点。
效果如下:

最后一个按钮样式和第一个其实是一样的,只不过最后是从sprite.png加载过来的,我使用了CSS 图片拼合生成器将四张图拼接起来了,然后再用CSS去定位。
拼接完成之后的图:sprite.png