1、为什么要用精灵图
网页上面的每张图片都要经历一次请求才能展示给用户,小的图标频繁的请求服务器,降低页面的加载速度,为了有效地减少服务器接收和发送请求的次数,提高页面的加载速度,因此,产生了css精灵技术。
2、主要使用的是background-position属性
比方说,在如图所示的字母图片中,我们想要A字母
(1)、设置一个容器div,设置其高度和宽度
(2)、设置背景图片,并且不重复
(3)、设置背景图片的位置,x,y(左上角是0,0)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 120px;
height: 120px;
background: url(images/abcd.jpg) no-repeat;
background-position: 0px 0px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
效果如图所示:
再举个例子,假设我们想要得到字母B
那么,我们的背景图片就需要往左边移动了哟,则x就是负值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 120px;
height: 120px;
background: url(images/abcd.jpg) no-repeat; // 设置背景图片
background-position: -120px 0px; // 背景图片需要往左边移动120像素
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
实现效果如图所示:
如果想要图片变小一点,还可以采用等比缩放的方式:transform: scale(0.5, 0.5);
<style>
.box {
width: 120px;
height: 120px;
background: url(images/abcd.jpg) no-repeat;
background-position: -120px 0px;
transform: scale(0.5, 0.5); // 长和宽分别缩小为原来的一半
}
</style>