Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Implementing image sprites in CSS

我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!

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, so the number of HTTP requests is reduced.

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

Full working demo at CSS Tricks

文件標籤與貢獻者

 此頁面的貢獻者: Sebastianz, teoli, xfq, Jeremie, kscarfone, i80and, Luke314
 最近更新: Sebastianz,