css- 精灵图的使用

250 阅读2分钟

认识精灵图

什么是CSS Sprite

CSS Sprite,又称精灵图,是一种CSS 图像合成技术,将各种小图标合并到一张图片上,然后利用CSS的背景定位来显示对应的图片部分.

也有人翻译为:CSS 雪碧,CSS精灵

使用CSS Sprite的好处

  • 减少网页的http请求数量,加快网页响应速度,减轻服务器压力
  • 减小图片总大小
  • 解决了图片的命名的困扰,只需要针对一张集合的图片命名

sprite 图片制作 (雪碧图,精灵图)

方法1: Photoshop,设计人员提供

方法2:网站在线生成:在线生成网站

精灵图的使用

精灵图的原理是通过只显示图片的很小一部分来展示的.

通常通过设置背景,来显示对应的图片

  1. 设置对应元素的宽度和高度
  2. 设置精灵图作为背景图片
  3. 调整背景图片的位置来展示

如何获取精灵图的位置

www.spritecow.com/

截屏2023-11-21 17.14.15.png

精灵图实践demo

1.动手生成精灵图

截屏2023-11-21 17.29.59.png

2.查看4张图片的定位位置

.sprite { background: url('imgs/css_sprites.png') no-repeat -10px -10px; width: 572px; height: 112px; }
.sprite { background: url('imgs/css_sprites.png') no-repeat -10px -142px; width: 368px; height: 160px; }
.sprite { background: url('imgs/css_sprites.png') no-repeat -398px -142px; width: 122px; height: 136px; }
.sprite { background: url('imgs/css_sprites.png') no-repeat -10px -322px; width: 184px; height: 180px; }

3.使用精灵图展示图片代码

<!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>
      .imgOne {
        background: url("imgs/css_sprites.png") no-repeat -10px -10px;
        width: 572px;
        height: 112px;
      }
      .imgTwo {
        background: url("imgs/css_sprites.png") no-repeat -10px -142px;
        width: 368px;
        height: 160px;
      }
      .imgThree {
        background: url("imgs/css_sprites.png") no-repeat -398px -142px;
        width: 122px;
        height: 136px;
      }
      .imgFour {
        background: url("imgs/css_sprites.png") no-repeat -10px -322px;
        width: 184px;
        height: 180px;
      }
      div {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div class="imgOne">图片: 1</div>
    <div class="imgTwo">图片: 2</div>
    <div class="imgThree">图片: 3</div>
    <div class="imgFour">图片: 4</div>
  </body>
</html>

效果图:

截屏2023-11-21 17.40.19.png