CSS - 图像精灵



CSS 图像精灵是 Web 开发中常用的一种技术,它将多个图像组合到一个图像文件中(精灵图像),并使用精灵图像内的坐标来显示图像。这种方法可以减少服务器请求次数,提高网站性能。

图像精灵通常用于网站上的图标、按钮和其他小型图形。然后使用 CSS 根据需要显示精灵图像的特定部分。

如何在 CSS 中实现图像精灵?

  • 创建精灵图像: 使用 Adobe Photoshop 等照片编辑工具,创建一个包含所有要用作精灵的单个图像的图像。
  • 确定图像位置: 您需要精确记录主精灵图像内所有子图像左上角的坐标,这些坐标稍后可在 CSS 代码中使用以呈现图像的该部分。
  • 显示图像: 使用属性background-image在网页中显示精灵图像。
  • 调整位置: 使用background-position指定精灵图像中内部图像的左上角。使用heightwidth属性指定应从左上角呈现多少尺寸。
.sprite-icon { width: 75px; /* Set the width of the displayed image */ height: 75px; /* Set the height of the displayed image */ background-image: url('sprites.png'); /* Path to sprite image */ background-position: -40px -40px; /* Position of the individual image within the sprite */ }

在上面的示例中,我们首先将子图像的高度和宽度指定为 75px。然后,我们指定了精灵图像的 URL,其中包含所有内部图像。然后,我们使用 background-position 属性将内部图像的左上角位置指定为 (-40px, -40px)。下图显示了根据上述值如何选择内部图像。

img-sprite

CSS 图像精灵基本示例

以下示例演示如何使用 CSS 图像精灵从单个图像文件显示多个图像。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> img{ height: 60px; width: auto; border: 3px solid; } .main{ display: flex; justify-content: space-around; } .bootstrap, .html, .css { width: 150px; height: 150px; background-image: url('/css/images/devices.png'); background-repeat: no-repeat; border: 5px solid; } .bootstrap { background-position: -5px -5px; } .html { background-position: -155px -5px; } .css { background-position: -277px -5px; } </style> </head> <body> <h3>Original Image</h3> <img src="/css/images/devices.png"/> <h3>Image sprites</h3> <div class="main"> <div class="bootstrap"> </div> <div class="html"> </div> <div class="css"> </div> </div> </body> </html>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS 图像精灵悬停效果

以下示例演示了如何在图像精灵上使用悬停效果,当您将鼠标悬停在图像上时,图像会变得稍微透明。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> img{ height: 60px; width: auto; border: 3px solid; } .main{ display: flex; justify-content: space-around; } .bootstrap, .html, .css { width: 150px; height: 150px; background-image: url('/css/images/devices.png'); background-repeat: no-repeat; border: 5px solid; } .bootstrap { background-position: -5px -5px; } .html { background-position: -155px -5px; } .css { background-position: -277px -5px; } .bootstrap:hover, .html:hover, .css:hover { opacity: 0.7; } </style> </head> <body> <h3>Original Image</h3> <img src="/css/images/devices.png"/> <h3>Image sprites</h3> <div class="main"> <div class="bootstrap"> </div> <div class="html"> </div> <div class="css"> </div> </div> </body> </html>
广告