Implementing image sprites in CSS - CSS: Cascading Style Sheets 编辑

Image sprites are used in numerous web apps where multiple images are used. Rather than include each image as a separate image file, it is much more memory- and bandwidth-friendly to send them as a single image; using background position as a way to distinguish between individual images in the same image file, so the number of HTTP requests is reduced.

Note: When using HTTP/2, it may in fact be more bandwidth-friendly to use multiple small requests.

Implementation

Suppose an image is given to every item with class toolbtn:

.toolbtn {
  background: url(myfile.png);
  display: inline-block;
  height: 20px;
  width: 20px;
}

A background position can be added either as two x, y values after the url()() in the background, or as background-position. For example:

#btn1 {
  background-position: -20px 0px;
}

#btn2 {
  background-position: -40px 0px;
}

This would move the element with the ID 'btn1' 20 pixels to the left and the element with the ID 'btn2' 40 pixels to the left (assuming they have the class toolbtn assigned and are affected by the image rule above).

Similarly, you can also make hover states with:

#btn:hover {
  background-position: <pixels shifted right>px <pixels shifted down>px;
}

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:112 次

字数:1964

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文