精灵图(雪碧图)CSS Sprites

95 阅读1分钟

CSND学习地址

雪碧图,是一种CSS图像合成技术,将小图标合并在一起之后的图片,每个小图标配合background-position来获取。 在一些需要非单向的平铺背景和需要网页缩放的情况下,CSS Sprites就很适用了。

<!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>
    .image_show{
      border: 1px solid red;
      width: 187px;
      height: 250px;
      background-image: url("./1.png");
      background-repeat: no-repeat;
      background-position: -266px -30px; 
    }
  </style>
</head>
<body>
  <div class="image_show"></div>
</body>
</html>

background-position:取小图标左上角像素的负数

width:图片的宽

height:图片的高

雪碧图的优点

  • 加快网页加载速度
  • CSS Sprites减少图片的字节

雪碧图的缺点

  • 图片之间需要留有一定的空间,防止出现不必要的背景
  • 宽屏下,高分辨率的屏幕的自适应页面,图片宽度不够,容易出现背景断裂。
  • 图片位置需要固定为某个绝对值,失去了center之类的灵活性