这里所说的切割不是真正的切割哈,只是用CSS取图片中的一部分而已。这样做有很多好处哦,最大的好处就是减少了打开网页时请求图片的次数。主要有两种方式,一是做为某一元素的背景图片,二是用<img>元素的属性。下面就来看看如何做哈!
方式一:
用CSS中元素的background : background-color || background-image || background-repeat || background-attachment || background-position
示例:background:transparent url(http://hi.csdn.net/attachment/201010/13/139538_1286966876A7AV.jpg) no-repeat scroll -140px -20px;
解释:transparent表示透明无颜色
url(http://hi.csdn.net/attachment/201010/13/139538_1286966876A7AV.jpg) 表示背景图片
no-repeat 表示图片不重复
scroll 表示背景图片随浏览器下拉而滚动
-140px 表示水平位置在图片的-140px处(以图片的左上角为0,0)
-20px 表示垂直位置在图片的-20px处(以图片的左上角为0,0)
实例:
<html> <head> <style type="text/css"> a { width:100px; height:35px; background:transparent url(http://hi.csdn.net/attachment/201010/13/139538_1286966876A7AV.jpg) no-repeat scroll -20px -20px; } a:hover { width:100px; height:35px; background:transparent url(http://hi.csdn.net/attachment/201010/13/139538_1286966876A7AV.jpg) no-repeat scroll -140px -20px; } <style> </head> <body> <a href="#" mce_href="#">测试</a> </body> </html>
方式二:
用img的clip属性中的rect,clip:rect(y1 y1 x2 x1)参数说明如下:
y1=定位的y坐标(垂直方向)的起点
x1=定位的x坐标(水平方向)的起点
y2=定位的y坐标(垂直方向)的终点
x2=定位的x坐标(水平方向)的终点
注:坐标的起点是在左上角
<html> <head> <style type="text/css"> img { position:absolute; clip:rect(20px 100px 50px 20px); } </style> </head> <body> <p><img border="0" src="http://hi.csdn.net/attachment/201010/13/139538_1286966876A7AV.jpg"/></p> </body> </html>
我们不难看出,控制图片显示的关键在于clip:rect(20px 100px 50px 20px)这句,
但是千万不要遗漏了position:absolute;这是用于使用绝对值来定位元素