精灵图的作用:
- 减少页面的图片数量
(不用在img包中添加很多小图标,只需一张包含很多图标的图片即可实现在某位置显示图上的某个图标); - 减少服务器接收和发送请求的次数,提高加载速度。
精灵图:小背景或小图标整合到一张大图中。
技术要领:
1.测量想要显示的图标的大小,在图片的位置,到上边缘和左边缘的距离(可在ps中用矩形工具或切图工具测)
2.设置一个跟图标大小一样或稍大的盒子,用来放图标;
3.把精灵图作为背景,设置背景的位置(根据测到的“到上边缘和左边缘的距离”)来将图标放在盒子中。
例子:
精灵图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.denglu{
// 1.设置盒子的大小
width: 60px;
height: 60px;
margin: 0 auto;
//2.把精灵图作为背景,并设置背景的位置
background: url(img/王者荣耀精灵图1.png);
background-position: -182px 0;
}
.box2{
width: 30px;
height: 30px;
//可以设置定位,改变盒子的位置,也就改变了图标的位置。
position: absolute;
left: 300px;
top: 400px;
background: url(img/王者荣耀精灵图1.png) -153px -105px;
}
</style>
</head>
<body>
<div class="denglu"></div>
<div class="box2"></div>
</body>
</html>
结果: