为什么需要精灵图?
一个网页中往往会应用很多小的背景图像作为修饰,当网页中的图像过多时,服务器就会频繁地接收和发送请求图片,造成服务器请求压力过大,这将大大降低页面的加载速度。
因此,为了有效地减少服务器接收和发送请求的次数,提高页面的加载速度,出现了CSS精灵技术(也称 CSS Sprites、CSS 雪碧)。
核心原理:将网页中的一-些小背景图像整合到一张大图中,这样服务器只需要一次请求就可以了。
精灵图(sprites)的使用:
使用精灵图核心:
1精灵技术主要针对背景图片的使用。就是把多个小背景图片整合到一张大图片中。
2这个大图片也成为sprites 精灵图或雪碧图
3移动背景图片位置,此时可以使用background-position
4移动的距离就是这个目标图片的x和y坐标。注意网页中的坐标有所不同
5因为一般情况下都是往上往左移动,所以数值是负值
6使用精灵图的时候需要精准测量,每个小背景图片的大小和位置。
<!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>精灵图使用</title>
<style>
.box1 {
width: 60px;
height: 60px;
background-color: pink;
margin: 50px auto;
background: url(images/sprites.png) no-repeat -182px 0;
}
.box2 {
width: 27px;
height: 27px;
background-color: aquamarine;
margin: 100px;
background: url(images/sprites.png) no-repeat -155px -106px;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
案例:拼出自己的名字
<!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>利用精灵图拼出自己的名字</title>
<style>
span {
display: inline-block;
background: url(images/abcd.jpg) no-repeat
}
.h {
width: 45px;
height: 55px;
background-position: -38px -70px;
}
.y1 {
width: 44px;
height: 54px;
background-position: -211px -202px;
}
.y2 {
width: 44px;
height: 54px;
background-position: -211px -202px;
}
</style>
</head>
<body>
<span class="h"></span>
<span class="y1"></span>
<span class="y2"></span>
</body>
</html>